简体   繁体   English

Javascript数组(内部带有对象)到PHP以插入数据库

[英]Javascript Array(With objects inside) to PHP to insert into a database

Right, I have an array which has objects inside and it looks like this: 是的,我有一个内部有对象的数组,看起来像这样:

带有对象的数组

I would like that to be inserted into my database through an AJAX call to my php file. 我希望将其通过对我的php文件的AJAX调用插入到我的数据库中。

I have tried JSON.stringfy on the array and the result i get back in the database is 我在数组上尝试了JSON.stringfy,返回数据库的结果是

[{"task":"Tyres","notes":"Hello","completed":"True"},{"task":"Tyres","notes":"All Four Tyres need doing","completed":"True"},{"task":"Tyres","notes":"All Four Tyres need doing","completed":"True"},{"task":"Tyres","notes":"All Four Tyres need doing","completed":"True"}] [{“任务”:“轮胎”,“注释”:“你好”,“完成”:“真实”},{“任务”:“轮胎”,“注释”:“所有四个轮胎都需要做”,“完成“:” True“},{” task“:”轮胎“,”注释“:”所有四个轮胎都需要做“,” completed“:” True“},{” task“:”轮胎“,”注释“: “所有四个轮胎都需要做”,“完成”:“正确”}]

The double quotes have been replaced with " I realise this is the symbol of the quotes however I would like the quotes. 双引号已替换为“我意识到这是引号的符号,但是我希望使用引号。

I also tried sending the array and the database returns blank. 我也尝试发送数组,数据库返回空白。

JavaScript代码

PHP代码

Is there a way around this? 有没有解决的办法?

You need to use PHP json_decode to translate back to object. 您需要使用PHP json_decode转换回对象。 But beware that it will convert back to StdClass only. 但是请注意,它将仅转换回StdClass。 You need to read it and handle proper transformations. 您需要阅读并处理正确的转换。 eg: 例如:

$carChecklist = json_decode($_POST['checklist']);
echo $carChecklist[0]->tyres;

Should return 'Tyres'; 应返回“轮胎”;

Use PHP Data Objects (PDO) for your database inserts. 将PHP数据对象(PDO)用于数据库插入。 It allows you to make prepared statements to prevent injection attacks. 它使您可以准备语句以防止注入攻击。 You won't need functions like "safeString" and can guarantee that what you put in is what you get out. 您将不需要“ safeString”之类的函数,并且可以保证您放入的内容就是您得到的内容。

Here's an example of what it looks like. 这是一个看起来像的例子。 You can see that parameters are named and we pass values in an array with the names as keys. 您可以看到参数已命名,并且我们在名称作为键的数组中传递了值。

$sql = "UPDATE mutable SET json=:json WHERE id=:id";
$statement = $dbh->prepare($sql);
$statement->execute([":json" => $json, ":id" => $id]);
$result = $statement->fetchAll(PDO::FETCH_ASSOC);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM