MySQL Database Contains Quotes Encoded And Unencoded And It's Breaking Javascript
Example database value is '12345' which is assigned to a PHP variable $name. This value is used in a javacript onclick event for example: onclick='assign('
Solution 1:
You should use language aware escaping routines where possible. addslashes
is almost never the right choice.
In this case, json_encode
will do the job as JSON is a subset of the bit of JavaScript that describes literals. Note it will also add the quotes to indicate that it is a string.
Once you make it safe for JavaScript, your existing choice of htmlspecialchars
is the right one to make that JavaScript safe for embedding in an HTML attribute value.
onclick="assign(<?php echo htmlspecialchars(json_encode($name));?>)
You could also consider using a data-
attribute to store the data in, and then binding your event handlers with addEventListener
.
Post a Comment for "MySQL Database Contains Quotes Encoded And Unencoded And It's Breaking Javascript"