JavaScript数组 - > PHP对象 - > mysql数据库 [英] Javascript array -> PHP object -> mysql database
问题描述
我在MySQL数据库中发送之前存储一些值客户端。
这里就是我所做的。
I store some values client side before sending them in a mysql database. Here's what I did.
我创建了一个名为脚本一个javascript数组,我使用此功能的客户端会话过程中添加一些行:
I create a javascript array named "script" and I add some rows during the client session using this function :
VAR脚本= [];
var script = [];
功能storestat(A,B,C,D){script.push({Idcat:一,Idquest:B,得分:
C,队报:D}); }
function storestat(a,b,c,d){ script.push({Idcat: a, Idquest: b, Score: c, Equipe: d}); }
然后,我用这样的AJAX发送这个数据
Then I send this data with ajax like this
function statquest(){
var postArray = JSON.stringify(script);
$.ajax({
url: 'statquest.php',
type: 'POST',
data: {data: postArray},
cache: false,
success: function(output){
dit = output;
},
error: function (request, status, error) {
}
});
}
在statquest.php,我得到的数据串和去code会这样:
In statquest.php, I get the data string and decode it like that :
$myarray = json_decode($_POST['data']);
下面是我所看到的,如果我用var_dump表明目的
Here's what i see if I use var_dump to show the object
array(2) { [0]=> object(stdClass)#3 (4) { ["Idcat"]=> string(1) "2" ["Idquest"]=> string(1) "4" ["Score"]=> int(3) ["Equipe"]=> int(5) } [1]=> object(stdClass)#4 (4) { ["Idcat"]=> string(1) "1" ["Idquest"]=> string(1) "6" ["Score"]=> int(3) ["Equipe"]=> int(2) } }
我要插入此JSON对象(所有行)成田被命名为喜欢的对象,一个MySQL数据库:Idcat,Idquest,分数和队报
I want to insert this json object (all rows) into a mysql database which fields are named like in the object : Idcat, Idquest, Score and Equipe
我试过类似的东西,但它不能正常工作
I tried something like that but it doesn't work
$sql = "INSERT INTO ".$mydatabase." (`Idcat`, `Idquest`, `Score`, `Equipe`) VALUES (:Idcat,:Idquest,:Score,:Equipe)";
$q=$pdo->prepare($sql);
foreach($myarray as $row=>$value){
$q->bindValue(":".$row,$value);
}
$q->execute();
我有这样的错误:
I have this error :
Catchable fatal error: Object of class stdClass could not be converted to string
任何想法的人?谢谢
Any idea someone ? Thank you
推荐答案
如果我看看你的var_dump()
If i look your var_dump() :
{ [0]=> object(stdClass)#3 (4) { ["Idcat"]=> string(1) "2" ["Idquest"]=> string(1) "4" ["Score"]=> int(3) ["Equipe"]=> int(5) } [1]=> object(stdClass)#4 (4) { ["Idcat"]=> string(1) "1" ["Idquest"]=> string(1) "6" ["Score"]=> int(3) ["Equipe"]=> int(2) } }
您数组$ myarray中的行不是一个数组:例如,如果我想读的第一行:
Your row of the array "$myarray" is not a an array to : For example, if I want to read the first line :
echo $myarray[0]->Idcat;
---编辑完成我的答复-----
---Edit to complete my reply-----
因此,对于你的情况,做这样的事情:
So, for your case, do something like that :
for($i=0;$i<sizeof($myarray);$i++){
foreach($myarray[$i] as $key => $val){
$q->bindValue(":".$key,$val);
}
//Execute your query here
}
这篇关于JavaScript数组 - &GT; PHP对象 - &GT; mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!