编辑回答下面的代码,这一个完美的工作。 ♥新年快乐,大家好♥PHP错误的foreach代码
$custom = "8-1,1-1,4-1,";
$product_id_string = $_POST['custom'];
$product_id_string = rtrim($product_id_string, ",");
$id_str_array = explode(",", $product_id_string);
foreach ($id_str_array as $key => $value) {
$id_quantity_pair = explode("-", $value); // Uses Hyphen(-) as delimiter to separate product ID from its quantity
$id = $id_quantity_pair[0]; // Get the product ID
$product_quantity = $id_quantity_pair[1]; // Get the quantity
$sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
while ($row = mysql_fetch_array($sql)) {
$product_name = $row["product_name"];
$product_price = $row["price"];
}
$product_price = $product_price * $product_quantity;
$message2 .= "<tr>";
$message2 .= "<td style='text-align:center'>" . $product_name . "</td>";
$message2 .= "<td style='text-align:center'>" . $product_quantity . "</td>";
$message2 .= "<td style='text-align:center'>" . $product_price . " €</td>";
$message2 .= "</tr>";
}
代码编辑,工作完美:)
1)'定制= '8-1,1-1,4-1';'是错误的(缺少'$')。 2)你用'foreach'迭代一个字符串,期望这些元素是关联数组3)你以不安全的方式使用mysql_query'并且不推荐使用该扩展 –
显示你实际的'$ custom'变量。 –