Error in mysql_fetch_object

Asked

Viewed 514 times

5

I don’t know what happens in this mistake.

Fatal error: Cannot use Object of type stdClass as array in

$result = mysql_query("select * from usuarios");
while ($row = mysql_fetch_object($result)) {
    echo $row["Id"];
    echo $row["Nome"];
}

4 answers

5


To access the return of mysql_fetch_object() use this syntax:

$row->nome_da_chave;

If you want to use associative arrays use mysql_fetch_assoc(), to access the items just

$row['nome_da_chave'];

It is highly recommended to use the PDO or mysqli to make connection to database, because the functions mysql_* have already been depreciated and will soon be removed.

Reasons for not using mysql functions_*

1

The function mysql_fetch_object returns an object of type \StdClass. To return an array, use the function mysql_fetch_array.

1

When you use the mysql_fetch_object the pointer return is always an object of type stdClass, so you cannot reference it with the Brackets because only arrays are referenced so, to reference it so you should use the mysql_fetch_assoc or mysql_fetch_array.

//utilizando mysql_fetch_assoc
$result = mysql_query("select * from usuarios");
while ($row = mysql_fetch_assoc($result)) {
    echo $row["Id"];
    echo $row["Nome"];
}

//utilizando mysql_fetch_object
$result = mysql_query("select * from usuarios");
while ($row = mysql_fetch_object($result)) {
    echo $row->Id;
    echo $row->Nome;
}

documentation http://www.php.net/manual/en/function.mysql-fetch-object.php

0

for objects use mysql_fetch_object for use array mysql_fetch_array for associative array mysql_fetch_assoc

  • 1

    You made no mention of the reason for the error, just put loose information. Your answer could be a little more explanatory, relating what you said to the problem faced.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.