PHP / MYSQL question

Status
Not open for further replies.

monkeyBox

Ars Scholae Palatinae
705
in ASP when using a recordset object, I can refer to a field like this:
code:<HR>
Code:
foo = rs("MY_FIELD")
if PHP you have to refer to it numerically, like this:
code:<HR>
Code:
$foo = $row[0];
Is there a way to refer to a field by its name? like this:
code:<HR>
Code:
$foo = $row["myField"]

I know that this is pretty measly, but it still would be nice not to have to memorize what order your fields are in.
 
If you take a look at the php docs for the mysql interface, there are a number of different functions you can use to fetch the record set. mysql_fetch_row() returns a numeric array, but if you use mysql_fetch_assoc() you will get an associative array.

Here is some code:

code:<HR>
Code:
$result = mysql_query('SELECT bar FROM foo');<P>while ($row = mysql_fetch_assoc($result))
{
    echo $row['bar'];
}
 

Statik

Ars Scholae Palatinae
1,451
Why foreach? do a while

ie.
code:<HR>
Code:
$sql = "select firstname, lastname, phone_number from customers";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
    $firstname = $row[0];
    $lastname = $row[1];
    $phone_number = $row[2];
    echo "$first_name, $lastname, $phone_number\n";
}

or

code:<HR>
Code:
$sql = "select firstname, lastname, phone_number from customers";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
    $firstname = $row['firstname'];
    $lastname = $row['lastname'];
    $phone_number = $row['phone_number'];
    echo "$first_name, $lastname, $phone_number\n";
}

Statik
 
Status
Not open for further replies.