dongxinjun3944 2014-04-26 22:25
浏览 30
已采纳

插入多个值数据库php时出错

Can someone explain me why this is not working, Im trying to insert multiple values into a database, first I was inserting carpirces only and was working, but now Im trying to insert also de Ids but now the code don't work

if(!empty($_POST))
{ 
  $query = "INSERT INTO prices (carid, vendorid, carprice) values (:carid, 2, :carprice)";
  $query_params = array(':carprice' => $_POST['carprice']);
  $price = null;
  $carids = null;
  try
  {
    $stmt = $db->prepare($query); 
    $stmt->bindParam(':carprice', $price);  
    foreach($_POST['carprice'] as $value) { 
            $price = $value;
            $stmt->execute();
    }
      $stmt->bindParam(':carid', $carids);  
    foreach($_POST['carid'] as $value) { 
            $carids = $value;
            $stmt->execute();
    }

  }
  catch(PDOException $ex)
  {
    die("Error 1 " . $ex->getMessage());
  } 
  header("Location: update.php");
  die("Rendirecting to update.php");
}
?>
<form action="prices.php" method="post">
<table border=1>
  <tr>
    <th>Id</th>
    <th>car</th>
    <th>model</th>
    <th>Price</th>
  </tr>
<?php foreach($rowscars as $row): ?>
  <tr>
    <th><input type="hidden" name="carid[]" value="<?php echo ' ' . htmlentities($row['carid'], ENT_QUOTES, 'UTF-8') . ' ';?>" /><?php echo '' . htmlentities($row['carid'], ENT_QUOTES, 'UTF-8') . '';?></th>
    <th><?php echo '' . htmlentities($row['car'], ENT_QUOTES, 'UTF-8') . '';?></th>
    <th><?php echo '' . htmlentities($row['model'], ENT_QUOTES, 'UTF-8') . '';?></th>

    <th><input type="text" name="carprice[]" value=""></th>
  </tr>
<?php endforeach; ?>
</table>
<input type="submit" value="Submit">
</form> 
  • 写回答

1条回答 默认 最新

  • duandai3964 2014-04-26 23:01
    关注

    I suppose you want to insert carPrice for specified carId. First you need to map each car id to car price, do smth like this:

    if (!empty($_POST['carid'] && $_POST['carprice']) {
       $carPrices = array_combine($_POST['carid'], $_POST['carprice']);
       foreach ($carPrices as $carId => $carPrice) {
          $stmt = $db->prepare($query); 
          $stmt->bindParam(':carprice', $carPrice);
          $stmt->bindParam(':carid', $carId);
          $stmt->execute();
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?