2014-01-06 47 views
0

我想從數組插入數據到MySQL表。如果我在例如數組三項中,echo的結果是Item1Item2Item3,但是在mysql表中只插入Item3。爲什麼它不重複插入表格?插入數組到表

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

這將產生N + 1問題嘗試一次插入所有值。使用一個查詢。 –

回答

0

嘗試是這樣的:

<?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')"; 
    ?> 
0

很常見的做法是使用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']); 
0

您可以使用準備好的語句爲好。我習慣於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:我剛剛意識到這是一個非常老的帖子。不知道它爲什麼被列在最新的Feed中。