Stichy
Stichy

Reputation: 1515

Php mysql results as array

I have a table like this:

Table: categories

id | name

1 | Foo

2 | Bar

PHP

In php I want to print out like $category[1] (the name of the choosen id)

So if I write:

echo $category[1];

The result will be "Foo"

Sadly I've only come this far...

$result = mysql_query("SELECT * FROM categories"); while($row = mysql_fetch_array($result))

Upvotes: 0

Views: 89

Answers (4)

hakre
hakre

Reputation: 197680

With old style mysql which does not have iterators for result-sets, you can create your own easily, for example in PHP 5.5 with a generator:

$rows = function($result)  {
    while ($row = mysql_fetch_array($result))
        yield $row;
};

An Iterator then can be converted into an array (if the Iterator alone is not sufficient yet):

$array = iterator_to_array($rows($result));

If you're below PHP 5.5, you can make use of FetchingIterator which works similarly.

Upvotes: 0

Stichy
Stichy

Reputation: 1515

This actually solved it!

$result = mysql_query("SELECT * FROM categories"); $data = array(); $x = 1; while($row = mysql_fetch_array($result)) { $data[$x] = $row['nam']; $x++; } echo $data[2];

Upvotes: 0

Pupil
Pupil

Reputation: 23948

You can do it like:

<?php
$result = mysql_query("SELECT * FROM categories");
?>
<table>
    <tr>
    <th>Id</th>
    <th>Name</th>
    </tr>

    <?php
    while($row = mysql_fetch_assoc($result)) {
    ?>
    <tr>
    <td><?php echo $row['id'];?></td>
    <td><?php echo $row['name'];?></td>
    <?php
    }
    ?>
    </tr>
</table>

Note: mysql_* is deprecated. Use mysqli_

Upvotes: 1

Mark Miller
Mark Miller

Reputation: 7447

$result = mysql_query("SELECT * FROM categories");
while($row = mysql_fetch_array($result)) {
    echo $row['id'] . ' ' . $row['name'] . '<br/>';
}

Result:

1 Foo
2 Bar

Upvotes: 1

Related Questions