Echo - two columns

Hi chaps, i don’t know if its more of a mysql solution or php…

i have a list of products and want to echo 2 columns containing 50/50 of the data, so for example if i had 20 products, there would be two lists of 10. The number of products will change over time, therefore does anyone know of a solution?

thanks in advance

b

Select 20 products from the database, then use PHP to split them into columns with 10 in each.

The PHP for this would go something like…


<div id="products">
  <?php foreach(array_chunk($products, 10) as $product_list): ?>
    <div class="list">
      <?php foreach($product_list as $product): ?>
        <?php echo $product['name']; ?>
      <?php endforeach; ?>
    </div>
  <?php endforeach; ?>
</div>

:slight_smile:

Thanks Anthony…im a little confused :slight_smile:

Using the query:

$query_Products = “SELECT * FROM items ORDER BY prodtitle ASC”;
$Products = mysql_query($query_Products, $faboc) or die(mysql_error());
$row_Products = mysql_fetch_assoc($Products);
$totalRows_Products = mysql_num_rows($Products);

Could you change the values :)…sorry product/products references lost me

thanks

Certainly.

I’ve added some comments that may help too.


<?php
# get 20 items from the database
$sql = 'SELECT * FROM items ORDER BY prodtitle ASC LIMIT 20;';
# execute the query
$res = mysql_query($sql);
# create an array to store the 20 items
$items = array();
# loop through the items from the database
while($item = mysql_fetch_assoc($res)){
  # save the item to our array
  array_push($items, $item);
}
?>
<html>
  <head>
    <title>Deom</title>
  </head>
  <body>
    <div id="products">
      <?php foreach(array_chunk($items, 10) as $item_list): ?>
        <div class="list">
          <?php foreach($item_list as $item): ?>
            <?php echo $item['prodtitle']; ?>
          <?php endforeach; ?>
        </div>
      <?php endforeach; ?>
    </div>
  </body>
</html>

hum i get the error

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given (line 10)

which is this section
while($item = mysql_fetch_assoc($res)){

have you created a database connection prior to this point?

That’s because the query failed, for some reason.

Replace with this bit and we’ll go from there.


# execute the query
$res = mysql_query($sql) or die(mysql_error());

Oops, my error, i referred to an old localhost connection :slight_smile:

Many thanks, works like a dream!

b