php - SQL插入多行,foreach

标签 php mysql arrays

我正在尝试将多个插入到我的数据库中,具体取决于返回的数组迭代次数。

插入工作正常,但插入的行数不超过 1 行,无论数组中有什么。

function createOrder(){

  $CustomerID = $_SESSION['CustomerID'];
  $BasketID = $_SESSION['BasketID'];

  // create a new entry with an OrderID
  $orders = new Basket;
  $orders->storeFormValues( $_POST );
  // Collect the OrderID returned from insertOrder(); and insert into 'Orders'
  $OrderID = $orders->insertOrder($CustomerID);

  // Populate OrderDetails with items in users Basket.
  $data = Basket::getBasket($BasketID);
  $results['basket'] = $data['results'];

  // Insert the order details into the orderDetails DB.
  $orders->insertOrderDetails($OrderID, $BasketID, $CustomerID, $results); 
};

和循环:

public static function insertOrderDetails($OrderID, $BasketID, $CustomerID, $results){
   $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

    // for each row insert into the DB
    foreach ( $results['basket'] as $row ) {
      $sql = "INSERT INTO OrderProducts (OrderID, ProductName, Price, Quantity) 
              VALUES (:OrderID, :ProductName, :Price, :Quantity)";

      $st = $conn->prepare( $sql );
      $st->bindValue( ":OrderID", $OrderID, PDO::PARAM_INT );
      $st->bindValue( ":ProductName", $row->ProductName, PDO::PARAM_STR );
      $st->bindValue( ":Price", $row->Price, PDO::PARAM_INT );
      $st->bindValue( ":Quantity", $row->Quantity, PDO::PARAM_STR );
      $st->execute();

   }
    $conn = null;
}

数组 $results 看起来像;

array(1) {
  ["basket"]=>
  array(2) {
    [0]=>
    object(Basket)#3 (10) {
      ["OrderID"]=>
      NULL
      ["CustomerID"]=>
      NULL
      ["OrderItemID"]=>
      NULL
      ["ProductID"]=>
      string(1) "9"
      ["Quantity"]=>
      string(1) "4"
      ["ProductName"]=>
      string(12) "Cheese Bagel"
      ["Price"]=>
      string(1) "1"
      ["NameType"]=>
      string(5) "Bagel"
      ["BasketProductID"]=>
      string(2) "25"
      ["BasketID"]=>
      string(1) "3"
    }
    [1]=>
    object(Basket)#5 (10) {
      ["OrderID"]=>
      NULL
      ["CustomerID"]=>
      NULL
      ["OrderItemID"]=>
      NULL
      ["ProductID"]=>
      string(1) "2"
      ["Quantity"]=>
      string(1) "1"
      ["ProductName"]=>
      string(15) "The British BLT"
      ["Price"]=>
      string(1) "3"
      ["NameType"]=>
      string(5) "Bagel"
      ["BasketProductID"]=>
      string(2) "26"
      ["BasketID"]=>
      string(1) "3"
    }
  }
}

非常感谢任何建议!

最佳答案

我在数据库中的主键未设置为自动增量。改变这个就解决了这个问题。一旦允许就会删除。感谢您的帮助

关于php - SQL插入多行,foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28412169/

相关文章:

php - 数据库仅从链接列表中吐出特定 ID 的行数据,而不是数据库中的所有行

php - 如何通过 PHP 导入读取 CSV 来提取 XML 属性?

php - 应用程序/控制台 sulu :security:user:create is working but sulu-login doesn't work

php - 在 UTF-8 字符串上使用数组索引时输出错误

php - preg_match 匹配扩展名为 .jpg/.png 的文件

java - 在 Java 中,二维数组是否比一维数组使用更多的资源?

PHP产品价格与数量不成倍增加

php - 包含一个 html 页面,并在页面呈现后丢弃 css 样式

php - 如何将这个 "R"公式翻译成MySQL/PHP?

mysql - 如何使用 order by 和 limit 获取多行