【发布时间】:2014-07-16 07:39:35
【问题描述】:
在将它们发送到 mysql 数据库之前,我会在客户端存储一些值。 这就是我所做的。
我创建了一个名为“脚本”的 javascript 数组,并在客户端会话期间使用此函数添加了一些行:
var 脚本 = [];
function storestat(a,b,c,d){ script.push({Idcat: a, Idquest: b, Score: c,装备:d}); }
然后我用这样的 ajax 发送这些数据
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 中,我得到数据字符串并像这样解码它:
$myarray = json_decode($_POST['data']);
这是我使用 var_dump 显示对象时看到的结果
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、Score 和 Equipe
我尝试了类似的方法,但它不起作用
$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();
我有这个错误:
Catchable fatal error: Object of class stdClass could not be converted to string
有人知道吗?谢谢
【问题讨论】:
-
因为你的值是一个对象? $row 等于 $myarray 中的数组索引,$value 是其中的所有内容,即整个对象(stdClass)。您尝试实现的功能并不像您想象的那样工作,您尝试使用绑定参数插入多行......这是可能的,但您绝对应该使用准备好的语句阅读批量插入。 . == 编辑:== 请检查一下!您无需先进行某种检查就按原样接受客户端对象!
-
我知道检查。我没有发布完整的代码来简化...
-
你在女巫线上有这个错误? $q->bindValue(":".$row,$value); ?
-
是的,错误就在该行。也许我应该改变我在 javascript 数组中存储数据线的方式,而不是使用对象数组...
标签: php mysql arrays foreach json