This is interesting and by that I mean incredibly frustrating.
I am passing this data to my php file via an ajax call: {"html":"<div>I'm a div!!</div>"}
I want to preface this next statement by saying that I do understand the reasons for not saving json to a database, but it does have a use here.
When I save this data to the database field, the field is empty. Now see this:
$in1 = file_get_contents('php://input'); //from ajax
var_dump($in1);
$in2 = '{"html":"<div>I\'m a div!!</div>"}';
var_dump($in2);
value of my ajax call:
string(33) "{"html":"<div>I'm a div!!</div>"}"
string(33) "{"html":"<div>I'm a div!!</div>"}"
Perfectly the same! Yet, $in2
will save to the database just fine!! While $in1
yields an empty field!!
To be certain, consider this:
if ($in1 === $in2) { echo "They're equal!"; }
Go figure...they're exactly equal, yet one will save correctly and the other won't. Amazing.
Further: mysqli
does not have this issue, so that narrows it down to being a PDO issue.
$query = "UPDATE plugin_instances SET config=(?) WHERE id=2";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $in1);
$stmt->execute(); //correct value in the db!!
I have now removed everything and this is the whole php file.
Non-working output Working output
The only difference between these two is the result of $stmt->rowCount()
.
The sample that correctly updates the field says int(0)
and the one that empties it says int(1)
.
$db = new PDO('mysql:host=localhost;dbname=disarray', 'root', 'temp');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
var_dump($db);
$params = [':foo'=>'{"html":"<div>I\'m a div!!</div>"}'];
var_dump($params);
$params = [':foo'=>file_get_contents('php://input')];
var_dump($params);
$query = "UPDATE plugin_instances SET config=:foo WHERE id=2";
var_dump($query);
try {
$stmt = $db->prepare($query);
var_dump($stmt);
$stmt->execute($params);
var_dump($stmt);
var_dump($stmt->rowCount());
}
catch (PDOException $e) {
echo $e->getMessage();
}