【发布时间】:2018-10-17 06:43:07
【问题描述】:
我正在尝试将一组 ID 插入到数据库表中,但目前它只插入 1 行,而它意味着要执行多行。我的 ID 数组只包含 (filmid) 有人知道问题出在哪里吗?
$pm = "2";
$id = "2";
if($stmt1->execute())
{
$films=array();
foreach($_SESSION['products'] as $key=>$product)
{
array_push($films, $product['filmid']);
$f_id = implode(",", $films);
$stmt2 = $this->conn->prepare("INSERT INTO `filmPurchase` (`fpid`, `payid`, `filmid`, `shopid`, `custid`, `price`) VALUES (NULL, :id, :f_id, :pm, :pm, '8')");
$stmt2->bindParam('pm',$pm);
$stmt2->bindParam('id',$id);
$stmt2->bindParam('f_id',$f_id);
$stmt2->execute();
}
}
我尝试使用以下方法遍历数组:
foreach($_SESSION['products'] as $key=>$product)
{
var_dump($key);
var_dump($product);
}
这是输出的:
int(29) array(4) { ["qty"]=> int(1) ["filmtitle"]=> string(45) "The Lord of
the Rings: The Return of the King" ["filmid"]=> string(2) "29" ["price"]=>
float(6.99) }
【问题讨论】:
-
您的数组中只有 1 项。
$f_id插入的时候也要绑定。 -
我立即看到的 3 个问题:您没有在显示的代码中定义
$pm或$id;如果你要使用prepare,你应该绑定所有的变量(查看'$f_id'),并且你不能使用相同的绑定参数两次(:pm, :pm)。您必须重命名其中一个。 -
我已经进行了这些更改,还添加了定义的 ID。但仍然在做同样的事情。
-
您可能还想重新考虑您的查询。您的循环将在第一个循环上推送
"The Lord of the Rings: The Return of the King",在第二个循环上推送"The Lord of the Rings: The Return of the King", "The Lord of the Rings: The Two Towers",... -
@aynber 可以使用相同的参数两次。