如何迭代关联数组并使用其值创建多个记录。
问题似乎是正确配置bind_param的变量。
array(2) {
[0]=>
object(stdClass)#4 (3) {
["number"]=>int(1)
["detail"]=>string(3) "one"
}
[1]=>
object(stdClass)#5 (3) {
["number"]=>int(2)
["detail"]=>string(3) "two"
}
}
PHP和MYSQL
foreach ($myArray as $key => $value){
$one = $value->number;
$two = $value->detail;
$sqlQuery = "INSERT INTO my_tab (number, detail) VALUES (?,?)";
if($statement = $conexion->prepare($sqlQuery)){
$statement->bind_param("is", $one , $two);
$statement->execute();
}else{
...
}
}
my_tab中的预期结果:
number detail
1 one
2 two
答案 0 :(得分:0)
我认为没有任何理由不这样做:
$sqlQuery = "INSERT INTO my_tab (number, detail) VALUES (?,?)"; // no need to include this in loop - it's just a static string
if ($conexion) { // make sure this is defined
foreach ($myArray as $key => $value){
$one = (int)$value->number; // enforce this type as int
$two = $value->detail;
$statement = $conexion->prepare($sqlQuery));
if ($statement) {
$statement->bind_param("is", $one , $two);
$statement->execute();
}else{
...
}
}
}