Question

I have this

<?php 

$id=0;

$sql = mysql_query("SELECT item_product,amount,quantity FROM products_added WHERE cookieid=$cookieid") or die(mysql_error());

while ($rows = mysql_fetch_array($sql)) {

$product        = $rows['item_product']; 
$amount         = $rows['amount']; 
$qty        = $rows['quantity']; 

?>

<input class="itemname" type="text" id="product_<?php echo $id++;?>" value="<?php echo $product;?>">
<input class="itemamount" type="text" id="amount_<?php echo $id++;?>" value="<?php echo $amount;?>">
<input class="itemqty" type="text" id="qty_<?php echo $id++;?>" value="<?php echo $qty;?>">

<?php } ?> 

But it returns this

<input class="itemname" type="text" id="product_1" value="Apples">
<input class="itemamount" type="text" id="amount_2" value="1.50">
<input class="itemqty" type="text" id="qty_3" value="10">

<input class="itemname" type="text" id="product_4" value="Bananas">
<input class="itemamount" type="text" id="amount_5" value="3.50">
<input class="itemqty" type="text" id="qty_6" value="5">

But i need this

<input class="itemname" type="text" id="product_1" value="Apples">
<input class="itemamount" type="text" id="amount_1" value="1.50">
<input class="itemqty" type="text" id="qty_1" value="10">

<input class="itemname" type="text" id="product_2" value="Bananas">
<input class="itemamount" type="text" id="amount_2" value="3.50">
<input class="itemqty" type="text" id="qty_2" value="5">

I know i could use the incremental id from my database rows however i need it to be clean and start at 1 every time.

Any help would be greatly appreciated.

I know its got something to do with a loop in a loop but can not seem to get the logic.

Cheers Jonny

Was it helpful?

Solution

As you might know $id++ is equivalent to $id = $id + 1. You are writing a new value into $id all the time.

Simple, don't increment every time:

<?php 

$id=1;

$sql = mysql_query("SELECT item_product,amount,quantity FROM products_added WHERE cookieid=$cookieid") or die(mysql_error());

while ($rows = mysql_fetch_array($sql)) {

$product        = $rows['item_product']; 
$amount         = $rows['amount']; 
$qty        = $rows['quantity']; 

?>

<input class="itemname" type="text" id="product_<?php echo $id;?>" value="<?php echo $product;?>">
<input class="itemamount" type="text" id="amount_<?php echo $id;?>" value="<?php echo $amount;?>">
<input class="itemqty" type="text" id="qty_<?php echo $id;?>" value="<?php echo $qty;?>">

$id++;

<?php } ?> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top