0

I've some issues with an array fetched from MySQL

$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
mysql_fetch_row($result);

echo $row[0]; // doesn't work
echo $row[1]; // doesn't work

but this work

echo $row["FirstFieldName"] //OK
...

how should I change the following code to make it work?

for ( $i = 0; $i < count( $row ); $i++ )
{
    echo $row[ $i ];
}

thanks

aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • Looking at your code it would seem as simple as you're forgetting to put $row = before your mysql_fetch_row call. That should be it. – Oldskool Dec 28 '11 at 08:27

5 Answers5

2

Do below changes. use mysql_fetch_array instead of mysql_fetch_row()

mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

 $result = mysql_query("SELECT id,email FROM people WHERE id = '42'");

$row=mysql_fetch_array($result);

for ( $i = 0; $i < count( $row ); $i++ )
{
    echo $row[ $i ];
}
1

Try using mysql_fetch_array() instead.

The three functions you should look into are:

mysql_fetch_row, mysql_fetch_array, and mysql_fetch_assoc

Each does things a little differently.

Try it this way:

$sql = "SELECT id,email FROM people WHERE id = '42'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
  echo $row[0];
}
Magento Guy
  • 2,493
  • 1
  • 16
  • 13
0
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
$row=mysql_fetch_array($result);

echo $row[0];
echo $row[1];

it will work

Deept Raghav
  • 1,430
  • 13
  • 14
0

mysql_fetch_row returns one row, so to be able to use it you should do :

while( $row = mysql_fetch_row( $result ) ) 
{
    echo $row["email"];
}

Otherwise, as Mike said you should use mysql_fetch_array()

Jérémy Dutheil
  • 6,099
  • 7
  • 37
  • 52
0

ie.... this takes all the retrieved keys/fields and intereates them and hands them off to $s which can then be placed into html..

foreach($row as $key=>$val){
      $$key = $val;
      $s.= "<tr><td>".$key."</td><td>
      <input type=text size=88 name='".$key."' value='".$val."'></td></tr>";
      }
// end your php then onward to html
    <table>
    <?php echo $s;?>
    </table>