tags:

views:

178

answers:

6

Let's say I have this query in PHP.

$a = mysql_query("SELECT * FROM `users` WHERE `id` = '1' ");

Which is nice and all, but I have a problem. How do I view the contents of $a, which I presume is an array like so:

Index          | Value
ID             | 1
Username       | Foo
Password       | Bar
...
A: 

Use mysql_fetch_assoc:

while($row = mysql_fetch_assoc($a))
{
    echo $row['index'] . ' | ' . $row['ID'] . ' | ' . 
         $row['username'] . ' | ' . $row['password'];
}

mysql_free_result($a);

I prefere mysql_fetch_assoc to mysql_fetch_row since it's not appreciably slower, and it gives you the ability to call fields by name (e.g.-`$row['index']).

You could also use mysql_fetch_array if you wanted the flexibility of referring to the row by index or by name. Really, just preference.

Eric
+3  A: 
while ($row = mysql_fetch_assoc($a)) {
    echo $row['id'];
    echo $row['username'];
    echo $row['password'];
}
Mr. Smith
A: 

see fetch_array fetch_assoc fetch_object for more informations.

Aif
A: 

Or use :

var_dump($a, true);

if you just want to see the entrys..

ArneRie
A: 

In PHP and its mysql functions, running mysql_query() returns an identifier that points to a result set. Therefore, you need mysql_fetch_assoc() or one of its brothers (mysql_fetch_array, mysql_fetch_object, mysql_fetch_row) to actually pass the returned id to mysql to get a result set back.

I should also note that these functions just return a single row and advance the internal pointer to the next row.

Austin Hyde
A: 

Whats wrong with mysql_fetch_row()? Combine with the list() language construct it works pretty well and offers strongly typed variable names. I've used this several times:

$a = mysql_query("SELECT * FROM `users` WHERE `id` = '1' ");

while(list($index,$id,$username,$password) = mysql_fetch_row($a))
{
    echo "Index | " . $index . "<br />"; // assuming this in HTML
    echo "ID    | " . $id . "<br />;
    echo "User  | " . $username . "<br />";
    echo "Pass  | " . $password . "<br />";
}
shanabus