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
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'] );
	}

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.