0

I am sorry for my lazy title. I hope that a moderator could improve it so the database won't get infected.

I got the following code (forum.php);

<?php

$res = $db->query('
  SELECT *
  FROM forums_categories
  ORDER BY category_id
');

while ($row = $db->fetch_array($res)) {
  $categories = array(
    'ID'   => $row['category_id'],
    'NAME' => $row['category_name']
  );

  echo '<pre>';
  print_r($categories);
  echo '</pre>';
}

And I got the following database structure;

|---------------|-------------------|
|  category_id  |  category_name    |
|---------------|-------------------|
|  1            | Example 1         |
|  2            | Example 2         |
|  3            | Example 3         |
|  4            | Example 4         |
|  5            | Example 5         |
|  6            | Example 6         |
|---------------|-------------------|

But my array only returns 1 value:

Array
(
    [ID] => 1
    [NAME] => Example 1
)

Oh and if somebody likes to know how my $db->fetch_array looks like:

<?php

function fetch_array($result)
{
return mysql_fetch_assoc($result);
}

How can I return all rows in my array? Thank you for reading and thank you for replying!

  • Just a reminder: Try not to use `SELECT *` - Reason: http://stackoverflow.com/questions/321299/what-is-the-reason-not-to-use-select – Musterknabe Oct 08 '13 at 15:38

1 Answers1

3

You're overwriting the previous value of $categories on each iteration

$categories[] = array(
    'ID'   => $row['category_id'],
    'NAME' => $row['category_name']
  );

You might also want to initialize an empty array

$categories = array();

before your loop to avoid warnings.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 1
    We're declaring variables not only to prevent warnings, because warning is not problem. It's only telling us that we have problem. – Elon Than Oct 08 '13 at 15:25
  • Thank you for your information. It still does return one row but I get the feeling I am close. –  Oct 08 '13 at 16:06