What I have done wrong, foreach code written below, but it seems not working:
JavaScript
x
$custom = "8-1,1-1,4-1,";
foreach ($custom as $each_item) {
$id = $each_item['id'];
$quantity = $each_item['quantity'];
$sql3 = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
while ($row = mysql_fetch_array($sql3)) {
$product_name = $row["product_name"];
$price = $row["price"];
} }
What I have to change in this foreach code? Thanks
Advertisement
Answer
first line, custom is not a variable (could be copy and paste error)
JavaScript
$custom
Then you are splitting a string using can array operator, you need to split that string first using:
JavaScript
$custompieces = explode(",", $custom);
Then, you have declared $custom as $each_item, but you then appear to be trying to access a sub array that doesn’t exist. $each_item[id] and $each_item[quantity] are not defined anywhere. I am guessing that you are trying to split the 8-1 into id-quantity, in which case you need to actually define those to be able to use them.
JavaScript
$pieces = explode("-", $each_item);
$id = $pieces[0];
$quantity = $pieces[1];
So your final code needs to be:
JavaScript
$custom = "8-1,1-1,4-1,";
$custompieces = explode(",", $custom);
foreach ($custompieces as $each_item) {
$pieces = explode("-", $each_item);
$id = $pieces[0];
$quantity = $pieces[1];
$sql3 = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
while ($row = mysql_fetch_array($sql3)) {
$product_name = $row["product_name"];
$price = $row["price"];
} }