Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get property of non-object MySQLi result [duplicate]

Tags:

php

mysqli

Got a bit of PHP code I'm struggling with - had a search around Google etc. and tried everything mentioned, but for some reason I'm having trouble solving it.

The problem is:

I have some code that is querying a database for the presence of a particular user.

The code (it's a method inside a class)

<?php
global $mysqli;
// Query specified database for value
$q = 'SELECT id FROM ' . $database . ' WHERE username = \'' . $username . '\'';
$r = $mysqli->query($q);
var_dump($r);
if ($r->num_rows) {
    // If row found username exists so return false
    return false;
}
...
?>

I've var dumped the result of the query ($r) and got this:

object(mysqli_result)#4 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }

This is correct, there should only be 1 row as above.

I do get this error linking to the line saying if ($r->num_rows) {

Notice: Trying to get property of non-object in FILE on line LINE

but I don't know why since the object is valid (as above) and it should be working fine. From what I can tell it seems to be going through alright, I'm just wondering why there's an error. I'm sure it's something simple but I'd appreciate any help.

like image 553
Rick Hanshaw Avatar asked Sep 07 '11 11:09

Rick Hanshaw


People also ask

How can you retrieve a particular row of data from a set of MySQLi results?

The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.

What does the mysqli_query () function do?

Definition and Usage. The mysqli_query() function accepts a string value representing a query as one of the parameters and, executes/performs the given query on the database.

What value does mysqli_query return?

Return Values ¶ For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN , mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return true .

How can I tell if MySQLi query has returned any result?

Use mysqli_num_rows to check if any rows were returned or not.


1 Answers

$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if (!$result) {
    trigger_error('Invalid query: ' . $conn->error);
}

check the error with mysqli_error() function

probably your query has some faults.

like image 145
kemalatila Avatar answered Sep 22 '22 06:09

kemalatila