【发布时间】:2012-01-24 04:27:57
【问题描述】:
我正在使用foreach 进行多次插入(有两级循环,因为每个产品可能有很多属性)。建议使用stmt,但不知道怎么做。
我知道从表单中检索数据的方式。我需要帮助将数据放入数据库。
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();
}
产品表:
id---code---name---description---categori_id---price
产品属性表:
id---product_id---code---color---size---stock
【问题讨论】:
-
你有没有尝试过?
-
我正在尝试使用 stmt 插入,但我想知道是否有更好的方法来做到这一点
标签: php mysql foreach insertion