Hello,

Basically I'm trying to create a simple shopping cart.

I have a table in my database with some products in, and I am trying to pull the products from the database into a multidimensional array then display the results in a table.

The code I am using to put the results into an array is as follows:

$results = array();
while ($row = mysql_fetch_array($result))
   $results[] = $row;

Now I have no idea if that is the correct way to do it, because this is the first time I am using arrays and I'm getting very confused.

I used the command "print_r" to show me the contents of the array and it seems a bit of a mess (but it could be right for all I know).

The contents of the array looks like this:

Array ( [0] => Array 
			( 	[0] => 3 [id] => 3 
				[1] => tshirt [name] => tshirt
				[2] => 323 [price] => 323  ) 

	[1] => Array 
		(   [0] => 4 [id] => 4 
			[1] => Boots [name] => Boots 
			[2] => 33 [price] => 33  ) 

	[2] => Array 
		(   [0] => 5 [id] => 5
			[1] => Sun Glasses [name] => Sun Glasses
			[2] => 33 [price] => 33  ) 
  )

It's when I try to display the results properly in a table that I get all sorts of problems, the latest of which is that I try to list the names of all the products in the table, but instead it ends up just showing the id, name, and price from the first result.

Can anybody please confirm that I am putting the results into an array correctly please, and maybe guide me on the best way to display the results.

I've tried hunting around the Internet but there aren't many useful links that I can find for putting mysql results into an array then displaying them.

Thanks very much, help is much appreciated.

    Kerant wrote:

    Can anybody please confirm that I am putting the results into an array correctly please, and maybe guide me on the best way to display the results.

    Yes, though if you are not going to use the numeric indices, you should use mysql_fetch_assoc() instead.

    Actually, you should use the PDO extension or the MySQLi extension instead of the MySQL extension, but that's another issue.

      If you slightly adjust the routine it would help you, as you can then refer directly to records by their product id:

      while ($row = mysql_fetch_array($result))
         $results[$row['id']] = $row; 
      
        leatherback;10893313 wrote:

        If you slightly adjust the routine it would help you, as you can then refer directly to records by their product id:

        while ($row = mysql_fetch_array($result))
           $results[$row['id']] = $row; 
        

        Thanks for that.

        Sorry if this sounds stupid, but how would I then refer directly to the records by their product id?

        Like I said I'm having some trouble getting my head around arrays, it's a lot to take in! Haha.

        Thanks alot.

          Kerant wrote:

          Sorry if this sounds stupid, but how would I then refer directly to the records by their product id?

          It depends on how you are going to loop over the array. In my opinion, leatherback's suggestion is not very useful in this case since you will have to loop over the entire array in the given order anyway.

            laserlight;10893321 wrote:

            It depends on how you are going to loop over the array. In my opinion, leatherback's suggestion is not very useful in this case since you will have to loop over the entire array in the given order anyway.

            I have been using a tutorial that displays the results in a table, but I tried to change it to display the products in individual div's that I had set out.

            <?php
              for ($i = 0; $i < count($results); $i++) {
            ?>
            	<div class="product" align="center">
            		<p><?php echo $results[$i]; ?></p>
            		<?php echo '<a href="' . $_SERVER['PHP_SELF'] .
                    '?buy=' . $i . '">Buy</a>'; ?>
            	</div>
            
            <?php
            }
            ?>

            But as you can probably tell by that, I have practically no idea what I'm doing, and that isn't working. :o

              That would only work if you use your original code. $results[$i] should be $results[$i]['name'].

                laserlight;10893328 wrote:

                That would only work if you use your original code. $results[$i] should be $results[$i]['name'].

                Ah yeah. That kind of works, but it only shows the product name for alternative results, and it gives a "Notice: Undefined offset:" error for the others.

                For example,

                Notice: Undefined offset: 0
                Tshirt
                Notice: Undefined offset: 2
                Boots

                  That's weird. I suggest that you use mysql_fetch_assoc instead:

                  $results = array();
                  while ($row = mysql_fetch_assoc($result)) {
                     $results[] = $row;
                  }

                  And then:

                  <?php
                  for ($i = 0, $count = count($results); $i < $count; ++$i):
                  ?>
                      <div class="product" align="center">
                          <p><?php echo htmlspecialchars($results[$i]['name']); ?></p>
                          <?php echo '<a href="' . $_SERVER['PHP_SELF']
                              . '?buy=' . (int)$results[$i]['id'] . '">Buy</a>'; ?>
                      </div>
                  <?php
                  endfor;
                  ?>

                    Ah that worked a treat!

                    Thanks so much.

                      Sorry to resurrect this thread, but I've come across another problem now.

                      The displaying of products now works fine, and I am able to "buy" the products so that they are placed into the session, but now I am having trouble displaying the products in the session into a table as a shopping cart.

                      The code I am basing the cart on is...

                      session_start();
                      if (!isset($_SESSION['cart'])) {
                        $_SESSION['cart'] = array();
                      }
                      
                      $items = array(
                        'Canadian-Australian Dictionary',
                        'As-new parachute (never opened)',
                        'Songs of the Goldfish (2CD Set)',
                        'Ending PHP4 (O\'Wroxey Press)');
                      
                      $prices = array( 24.95, 1000, 19.99, 34.95 );
                      
                        $total = 0;
                        for ($i = 0; $i < count($_SESSION['cart']); $i++) {
                          echo '<tr>';
                          echo '<td>' . $items[$_SESSION['cart'][$i]] . '</td>';
                          echo '<td align="right">$';
                          echo number_format($prices[$_SESSION['cart'][$i]], 2);
                          echo '</td>';
                          echo '</tr>';
                          $total = $total + $prices[$_SESSION['cart'][$i]];
                        }
                      

                      I have tried changing the "items" and "prices" variables to the same as how they are displayed on the catalogue page, but they are not being displayed properly and I can't figure out why.

                      Could anybody help please?

                      Thanks.

                        Not without knowing what's supposed to be in $SESSION['cart'], but:

                        1. [man]foreach[/man] is often an easier way to loop through all the elements of an array, especially if you might be a bit hazy about what indices it has.

                        2. Having two separate arrays for $items and $prices is ugly and potentially hazardous as there's no relationship between, for example, "Songs of the Goldfish (2CD Set)" and 19.99. You could store these in one array instead.

                          $products = array(
                          	17=>array('item'=>'Canadian-Australian Dictionary', 'price'=>24.95),
                          	42=>array('item'=>'As-new parachute (never opened)', 'price'=>1000),
                          	...
                          );

                          Where the product array indices are the IDs of the products and are also stored in the array in $_SESSION['cart'] (assuming it's a bit excessive to store the product information itself directly in the session. Then the loop would be

                            $total = 0;
                          	foreach($_SESSION['cart'] as $cart_item)
                          	{
                          		echo '<tr>';
                          		echo '<td>'.$products[$cart_item]['item'].'</td>';
                          		echo '<td>'.number_format($products[$cart_item]['price'], 2).'</td>';
                          		echo '</tr>';
                          		$total += $products[$cart_item]['price'];
                          	}
                          
                        3. One further small point is that floating point numbers don't store exact decimals; there's a bit of fuzz around them. 24.95 is actually stored as 24.9499999999999992894573. This may become an issue at some stage.

                          Ah brilliant.

                          Thanks Weedpacket, and thanks for everyone else's help.

                          This thread is definitely resolved now🙂

                            Write a Reply...