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!

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

We're declaring variables not only to prevent warnings, because warning is not problem. It's only telling us that we have problem.
Thank you for your information. It still does return one row but I get the feeling I am close.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.