【问题标题】:How do I insert an array of id into database MySQL?如何将 id 数组插入数据库 MySQL?
【发布时间】: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 可以使用相同的参数两次。

标签: php mysql arrays pdo


【解决方案1】:

如果您的占位符是:id:pm(如prepare()),那么您必须在bindParam() 中使用:id

See php documentation

【讨论】:

  • 他们现在不这样做吗?我觉得你应该再看一遍他们的代码,看看下面的 cmets。
  • 你说得对,同时,有人评论了f_id,作者编辑了他的代码,所以我删除了这个提及
猜你喜欢
  • 2016-11-29
  • 1970-01-01
  • 2014-04-26
  • 2015-06-18
  • 2011-07-05
  • 2011-08-06
  • 2011-10-25
  • 2014-07-21
相关资源
最近更新 更多