0

I am fetching a row from a database using something like this

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

This example shows accessing $row using an index, like $row[0], but this is a path to error. I would like to do it like $row['id'] or $row['email']... how is that possible?

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
Duck
  • 34,902
  • 47
  • 248
  • 470
  • Use either PDO or MySQLi – verisimilitude Dec 01 '12 at 09:08
  • 1
    [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained and the [deprecation process](http://j.mp/Rj2iVR) has begun on it. See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). – Madara's Ghost Dec 01 '12 at 09:10

2 Answers2

4

Use mysql_fetch_assoc instead of mysql_fetch_row:

$row = mysql_fetch_assoc($result);

(That gives you the "associative array", so that you can fetch columns by their name.)

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
1

You can use mysql_fetch_assoc() instead of mysql_fetch_row()

0xmtn
  • 2,625
  • 5
  • 27
  • 53