Jump to content

While loop doesn't work. Help!


c_pattle

Recommended Posts

I have a table called "users_cart" where it products in a users cart are stored.  They are stored in the columns "product1", "product1_price", "product2", "product2_price" etc. 

 

I am trying to use the following loop to print them out onto the screen but can't seem to get it to work.  $count always seems to be stuck at 2. 

 


$cart_qry = 'select * from users_cart where username="' . $_SESSION['username'] . '"';
$cart_rs = mysql_query ( $cart_qry, $conn ) or die ('error query1' . mysql_error());

$count = 1;
	while ( $row = mysql_fetch_array ( $cart_rs ) ) {
		$_SESSION['display_cart'] = "<tr><td>" . $row['product' . $count . ''] . "</td><td>" . $row['product' . $count . '_price'] . "</td></tr>";
		$_SESSION['cart_total'] += $row['product' . $count. '_price'];
		$_SESSION['cart_item_total'] + 1;
		$count = $count + 1;
		echo ( $count );
		echo ( $_SESSION['display_cart'] );
	}

Link to comment
https://forums.phpfreaks.com/topic/203194-while-loop-doesnt-work-help/
Share on other sites

Yeah I tried that but it still doesn't work.  $count it always on 2.  Plus now it prints out $_SESSION['display_cart'] twice for some reason now. 

 

$count = 1;
	while (( $row = mysql_fetch_array ( $cart_rs ) ) and ($count < 4)) {
		$_SESSION['display_cart'] .= "<tr><td>" . $row['product' . $count . ''] . "</td><td>" . $row['product' . $count . '_price'] . "</td></tr>";
		$_SESSION['cart_total'] += $row['product' . $count. '_price'];
		$_SESSION['cart_item_total'] + 1;
		$count++;
		echo ( $count );
		echo ( $_SESSION['display_cart'] );
	}

To start with, your table design is horrific. You have all the products/prices stored in one row, using separate columns. Your table should have an order id, the user id (or username) and the product id and quantity, one row for each product in their cart.

 

Your code is attempting to loop through the rows for the user, but your table design only has one row with multiple columns. For your current table design, you would need to reference each of the "productx", "productx_price" columns in that single row.

 

I recommend fixing your table design. It will result in the simplest and fastest code.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.