I recently found myself in this dilemma while programming a chunk of my application.
I get the following error: Cannot use object of type mysqli_result as array
However, my application is turning the result into an array before trying to either return it or echo it.
The code is inside a method definition. And yes, I have tried everything I could, including searching this site, including all the questions marked as duplicate. No awnsers.
Here is the code after I tried a solution:
public function lookupEmailByUsername($username)
{
$database = new mysqli(APP_DB_HOSTNAME, APP_DB_USERNAME, APP_DB_PASSWORD, APP_DB_DATABASE, APP_DB_PORT);
$database->select_db("users"); // better safe than sorry
$row = $database->query("SELECT * FROM `users` WHERE `username` = \"$username\";");
if($row->num_rows == 1){
$finalRow = $database->query("SELECT * FROM `users` WHERE `username` = \"$username\";");
$finalRow->fetch_array();
$finalresult = $finalRow['email'];
return $finalresult; // Line where error occurs
} else {
$Logger = new logger();
$Logger->logEvent("ERROR", "Could not find user $username for reverse lookup", true, 1);
return null;
}
}
logger()
is my logging class and it has no problems.
Code before I tried a solution:
public function lookupEmailByUsername($username)
{
$database = new mysqli(APP_DB_HOSTNAME, APP_DB_USERNAME, APP_DB_PASSWORD, APP_DB_DATABASE, APP_DB_PORT);
$database->select_db("stories_users");
if(!$database->query("SELECT * FROM `users` WHERE `username` = \"$username\";")){
$logger = new logger();
$logger->logEvent("ERROR", "Unable to execute search SQL for email lookup");
return null;
}
$row = $database->query("SELECT * FROM `users` WHERE `username` = \"$username\";");
if($row->num_rows == 1){
$row->fetch_assoc();
return $row['email'];
} else {
$Logger = new logger();
$Logger->logEvent("ERROR", "Could not find user $username for reverse lookup", true, 1);
return null;
}
}
But when I return $row['email']
, the error occurs.
Doing a var dump like this: var_dump($row->num_rows)
returns 1, which is exactly what I am looking for. Why? Because if there is one row, it means there is one user. And my app doesn't allow duplicate users. This means the SQL is correct.
Why is return $row['email']
outputting that error when I tried to use fetch_array
and fetch_assoc
? There is one row as described above, and fetch_assoc
should have turned it into an array.
OPS: I just found that row
is not an array:
if(is_array($row)){
echo "row is array";
exit;
}
else {
echo "row is not array";
exit;
}
But I used fetch_assoc
. Sorry, I'm new to MySQLi's object oriented part.