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.
The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.
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.
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 .
Use mysqli_num_rows to check if any rows were returned or not.
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With