MySQL & numeric keys - is this a valid query?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
ambivalent
Forum Contributor
Posts: 173
Joined: Thu Apr 14, 2005 8:58 pm
Location: Toronto, ON

MySQL & numeric keys - is this a valid query?

Post by ambivalent »

Assume the following fictitious query:

Code: Select all

$result = mysql_query("SELECT firstName, lastName, FROM people");

echo "<table>";

while($dbResult = mysql_fetch_array($result)) {
     echo "<tr><td>".$dbResult['0']."</td>";
     echo "<td>".$dbResult['1']."</td></tr>";
     }

echo "</table>";
With respect to echoing out each element, I was kind of surprised that this seemed to work by calling a numeric reference, as opposed to the normal method, being "$dbResult['firstName']". I can't recall coming across this in anything I've read thus far (or maybe it went over my head at the time) and was wondering if indeed it was a valid way to loop through the data. The manual says:
mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both
so I'm assuming this is an instance of "both"?

Are there advantages/disadvantages to using one over the other?
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

You should use either:

Code: Select all

$result = mysql_query("SELECT firstName, lastName, FROM people");

echo "<table>";

while($dbResult = mysql_fetch_array($result)) {
     echo "<tr><td>".$dbResult[0]."</td>";
     echo "<td>".$dbResult[1]."</td></tr>";
     }

echo "</table>";
Or:

Code: Select all

$result = mysql_query("SELECT firstName, lastName, FROM people");

echo "<table>";

while($dbResult = mysql_fetch_array($result)) {
     echo "<tr><td>".$dbResult['firstName']."</td>";
     echo "<td>".$dbResult['lastName']."</td></tr>";
     }

echo "</table>";
Using both creates duplication of values, with one set having numeric values for the keys, the other having strings containing the alias of the columns.

If you wish to 'cut down' and use only the strings, then the command mysql_fetch_assoc() is your friend.
User avatar
ambivalent
Forum Contributor
Posts: 173
Joined: Thu Apr 14, 2005 8:58 pm
Location: Toronto, ON

Post by ambivalent »

Thanks, I learned something new today. 8O
Post Reply