user3308052 user3308052 - 1 year ago 48
Javascript Question

Post escaped Javascript array and unescape it in PHP

I have some javascript code that gets the value of two html form input fields. I escaped the values to allow users to enter in special characters and then placed them into an array that is stringified and then posted.

$(document).ready(function() {
$("#submit").click(function() {
var BuilderName = escape($('[name=BuilderName]').val());
var OwnersName = escape($('[name=OwnersName]').val());
var arraydata = [BuilderName, OwnersName];
$.post("DCF_Update_Query.php", {
data: JSON.stringify(arraydata)
}, function() {
}).fail(function() {

In my PHP file I retrieve and decode the array and insert it into my database.

$data = json_decode($_POST['data']);

mysqli_query($conn,"INSERT INTO dcf (BuilderName, OwnersName)
VALUES ('$data[0]','$data[1]')");

My problem is that the escaped characters are entering in the database as
, etc.. How can I un-escape those characters and then re-escape them using
. Also, I've heard that
automatically escapes special characters. If this is the case, then do I even need to escape them with
? I'd greatly appreciate any help, Thanks!

Answer Source

You really, really, REALLY need a prepared statement here. No escaping needed

$prep = $conn->prepare("INSERT INTO dcf (BuilderName, OwnersName) VALUES (?, ?)");
$prep->bind_param('ss', $data[0], $data[1]);