【问题标题】:Inserting array into table将数组插入表中
【发布时间】:2014-01-06 23:23:13
【问题描述】:

我正在尝试将数据从数组插入 mysql 表。例如,如果我在数组中有三个项目,则回显的结果是 Item1Item2Item3,但在 mysql 表中只插入了 Item3。为什么它不重复插入表格?

<?php
session_start();
foreach($_SESSION['cart'] as $item){
    $sql="INSERT INTO eshopadmin (Item)
          VALUES
          ('$item[item]')";
    echo $item[item];
}
?>

【问题讨论】:

  • 这将产生 N+1 问题尝试一次插入所有值。使用一个查询。

标签: php mysql sql arrays


【解决方案1】:

试试这样的:

 <?php
    session_start();
    $data; //array that will store all the data
    foreach($_SESSION['cart'] as $item){
      // push data to the array
      array_push($data,$item[item]);

      $data= implode(",", $data);
    }
       $sql="INSERT INTO eshopadmin (Item)
              VALUES
              ('$data')";
    ?>

【讨论】:

    【解决方案2】:

    使用implodeexplode 从数据库表字段中检索数组是非常常见的做法。

    $array = array('a','b','c');
    $sql = 'INSERT INTO eshopadmin (Item) VALUES ("'.implode(',', $array).'")';
    

    数组存储为a,b,c

    当检索它时:

    $row = mysql_fetch_assoc($result);
    $array = explode(',', $row['Item']);
    

    【讨论】:

      【解决方案3】:

      您也可以使用准备好的语句。我已经习惯了 MySQLi。

      <?php
      // loop only if cart is array and has items
      if( is_array( $_SESSION['cart'] ) && count( $_SESSION['cart'] ) ){
          // autocommit off
          $mysqli_instance->autocommit( false );
          // prepare insert sql
          $insert_statement = $mysqli_instance->prepare( '
              INSERT INTO eshopadmin
                  ( Item )
              VALUES
                  ( ? )
          ' );
          // bind variables to the statement
          $insert_statement->bind_param( 'i', $item_array_item_value );
          // loop throught array
          foreach( $_SESSION['cart'] as $item ){
              $item_array_item_value = $item['item'];
              $insert_statement->execute();
          }
          // manually commit
          $mysqli_instance->commit();
          // restore autocommit
          $mysqli_instance->autocommit( true );
      }
      

      PS:我才意识到这是一篇很老的帖子。不知道为什么它会在最新的提要中列出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-10
        • 1970-01-01
        • 1970-01-01
        • 2017-07-10
        • 2013-05-06
        • 2014-05-10
        相关资源
        最近更新 更多