Page 1 of 1

MySQL & numeric keys - is this a valid query?

Posted: Sat Oct 22, 2005 3:40 pm
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?

Posted: Sat Oct 22, 2005 4:09 pm
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.

Posted: Sat Oct 22, 2005 4:51 pm
by ambivalent
Thanks, I learned something new today. 8O