正在使用foreach
(有兩個級別的循環,因爲每個產品可能有很多屬性)進行多重插入。建議使用stmt,但不知道如何做到這一點。使用foreach 2級數組循環多重插入
我知道從表單中檢索數據的方式,而且我需要將數據放入數據庫。
Array ([1] => Array (
[category] => 1
[code] => NFK50889922
[price] => 15.00 [name] => Pendants
[description] => Gold pendants covered with 400k diamond
[thumbnail] => 131120091585.jpg
//second level array for attribute
[attcode] => Array ([0] => [1] => [2] =>)
[color] => Array ([0] => [1] => [2] =>)
[size] => Array ([0] => [1] => [2] =>)
[stock] => Array ([0] => [1] => [2] =>)))
代碼:
// Check for a form submiss
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$product=$_POST['product'];
foreach($product as $productcount){
$q = 'INSERT INTO product(id,code,name,description,category_id,price,icon) VALUES (NULL,'.$productcount['code'].',"'.$productcount['name'].'",'.$productcount['description'].',"'.$productcount['category'].',"'.$productcount['price'].',"'.$productcount['thumbnail'].')';
mysqli_query($dbc, $q);//insertion of general information of current product
//insertion of many attribute of current product
$sql = 'INSERT INTO product_attribute (product_id,code,c_value,s_value,stock) VALUES (LAST_INSERT_ID(), ?, ?, ?, ?)';
// Prepare the statement:
$stmt = mysqli_prepare($dbc, $sql);
// For debugging purposes:
// if (!$stmt) echo mysqli_stmt_error($stmt);
mysqli_stmt_bind_param($stmt,'sssi',$attribute_code,$color_value,$size_value,$stock_unit);
foreach($productcount['code'] as $attcode){
$attribute_code=$attcode;
}
foreach($productcount['color'] as $attcolor){
$color_value=$attcolor;
}
foreach($productcount['size'] as $attsize){
$size_value=$attsize;
}
foreach($productcount['stock'] as $attstock){
$stock_unit=$attstock;
}
foreach($productcount['attcode'] as $attcode){
$attcode;
}
// Execute the query:
mysqli_stmt_execute($stmt);
$stmt->close();
}
表prodcut:
id---code---name---description---categori_id---price
表產品屬性:
id---product_id---code---color---size---stock
你嘗試過什麼? – Indranil 2011-12-20 06:25:03
我試圖插入stmt,但我想知道是否有更好的方法來做到這一點 – 2011-12-20 06:38:39