i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("
{$query}
*** {$err} ***
");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '';
foreach($row as $key => $field) {
echo '' . htmlspecialchars($key) . ' ';
}
echo ' ';
}
echo '';
foreach($row as $key => $field) {
echo '' . htmlspecialchars($field) . ' ';
}
echo ' ';
}
echo("
");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in (OPTIONAL) dies with display of query string and mysql_error, if query fails. Example Output: so displays properly.
Id Name
777 Aardvark
50 Lion
9999 Zebra