user3308052 user3308052 - 3 months ago 10
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() {
alert('Successful');
}).fail(function() {
alert('Failed');
});
});
});


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
%26
,
%27
, etc.. How can I un-escape those characters and then re-escape them using
mysqli_real_escape_string()
. Also, I've heard that
json_decode()
automatically escapes special characters. If this is the case, then do I even need to escape them with
mysqli_real_escape_string()
? I'd greatly appreciate any help, Thanks!

Answer

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]);
$prep->execute();