I am using the PHP function mysqli_query to run a SELECT query.
What does mysqli_query return if the query runs successfully, but the query finds no matches?
Per the manual:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
A query that runs but returns no results is still considered a "successful query", since the query did run in the database and an empty result set is a legitimate response. This means the query will still return a mysqli_result object, and if you check its row count (either via $result->num_rows in the object-oriented style or mysqli_num_rows($result) in the procedural style) it will return 0.
A Mysqli_query object, than you can use mysqli_num_rows to count the number of rows returned. So:
if(mysqli_num_rows($query) > 0 ){
// Do something
}
if ($result = $mysqli->query("SELECT * FROM data"))
{
$count = $result->num_rows;
printf("Result set has %d rows.\n", $count);
$result->close();
}
From reference:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
Related
if(isset($_POST['saveUserName'])){
$newUserName = $_POST['newUserName'];
$id = $_SESSION['id'];
$sql = "UPDATE users SET user='$newUserName' WHERE id='$id';";
$result = mysqli_query($conn, $sql);
$result = mysqli_fetch_all($result);
}
This code shows me the following error:
Warning: mysqli_fetch_all() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\loginsystem\modify.php on line 13
Can you tell me what's wrong in this code ???
Thank you..
mysqli_query() function returns,
For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will return a mysqli_result object. For other successful queries it will return TRUE. FALSE on failure.
Here, $result contains true or false. That's why you got that particular error message.
The mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.
If you want to get a result set then you need to change the query to select or show something.
I'm trying to turn the below query into a prepared statement, but I'm having no luck so far. I've attached one of my attempts. The idea is I'm using this to check how many rows are returned using mysqli_num_rows afterward.
$sql2=mysqli_query($bd, "SELECT address FROM member WHERE address='".$address."'");
This is my attempt at creating a prepared statement.
$ustmt = $bd->prepare("SELECT username FROM member WHERE username = ?");
$ustmt->bind_param("s", $username);
$sql2 = $ustmt->execute();
Is this correct? And if so, how do I then check the number of rows returned into $sql2 ?
Yes, your preparation and execution is correct.
The execute call returns a boolean value, which will be true if successful else false (if false, the $stmt->error property will be set with error message).
This is worth checking before continuing, cause if its false, there will be no result.
Same with the preparation, if the $mysqli->prepare(...) call returns false, the $mysqli->error will be set with the error message.
After execution, you can fetch the number of affected rows by either the $num_rows property, in case its a SELECT statement, or the $affected_rows property in other cases.
echo $stmt->num_rows;
Or, you can fetch the mysqli_result object from the statement with the get_result() method.
The mysqli_result object contains the public field $num_rows, so you can check row count by:
$res = $stmt->get_result();
echo $res->num_rows;
For other methods in the mysqli_result object, i recommend checking the docs.
This SQL query return result and then session save empty variable like $_SESSION["fbid"] = $user->fbid; and array would be Array ( [fbid] => ).
$result = $mysqli->query("SELECT * FROM `users` WHERE `fbid` = '$fbid'") or die(mysqli_error());
if ($result) {
$user = $result->fetch_object();
...
The main question is, why is it passing through if ($result) when there isn't any records in the database?
You are saying if($result)
This states that your if will always be true.
You need to say if($result == 1) for example.
You need to have $result equal, or not equal.
That is how an if statement works. However, you are saying "if query" which wont work anyways, you need to say something like,
if(mysqli_num_rows($result) > 0){
$user = $result->fetch_object();
}
mysqli->query returns either true, or false or mysqli_result object.
Both true and mysqli_result object will pass if($result), and false returned in case of error. Getting empty result is not an error.
If you need to check if your query returns empty result, use $num_rows property, for example.
Your test if ($result) will only fail if mysqli_query() fails, perhaps with a syntax error.
If you have a valid query your test will pass. This is true even if your valid query returns an empty set (Finding nothing is a valid result).
You need to check the result of the query to ensure your query actually succeeded, but this is different from checking whether it returned anything.
Try
$result = $mysqli->query("select...");
if ($result->num_rows) {
// do stuff
}
mysqli::query returns FALSE if a query fails. In this case, it did not fail - it was successfully executed, and returned zero rows.
If you want to check for an empty result set, check the return value of fetch_object:
$user = $result->fetch_object();
if ($user) {
# do stuff...
I've been running the query oh phpMyAdmin and it shows all the rows, but my query in php only returns the first row.
$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'");
print(count($result)); //always returns 1
for ($x = 0; $x < count($result); $x++) {
$row = mysqli_fetch_row($result);
}
For reference, here's why count() is returning 1. From the manual:
If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable [the parameter] is NULL, 0 will be returned.
Since $result is a resource (object) that is returned from your query, not an array which you would get within your loop getting the actual data out of the resource, count($resource) will return 1.
Your solution is of course to use mysqli_num_rows(). To retrieve data from this resource, you need to loop over it as you are doing, but either use mysqli_num_rows() in place of count(), or other (more common) ways of looping through a result set, like so:
while($row = mysqli_fetch_row($result)) {
// do stuff
}
You have to use mysqli_num_rows($result) function to count rows which are returned by MySQLi query.
Try this
echo mysqli_num_rows($result);
while($row = mysqli_fetch_row($result)) {
// write your code...
}
Use this instead of the for loop
the first thing that the query method returns to you is a resource/object. This query method always return a mysqli_result object for successful queries using SELECT, SHOW, DESCRIBE or EXPLAIN queries . For other successful queries mysqli_query() will return TRUE. For that reason it always count it as "1", what you should try is:
$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'");
$numRows = $result->num_rows;
print(count($numRows)); //it should show you the total amount of rows
//verify the amount of rows before of tryng to loop over it
if ($numRows) {
while($object = mysqli_fetch_object($result)){
//for each loop you will have an object with the attributes of the row
echo $object->song_name;
}
}
This should work,
Regards.
So I want to do a mysql_query - and I want to tell if a resource is null (that is, was unable to pull any values). Would the query be returned as false if no values were present? Am I reading the documentation right on this?
You can count the number of returned rows with mysql_num_rows(), and check how many were received from the query.
$results = mysql_query("SELECT * FROM...");
if(mysql_num_rows($results) > 0 ) {
// Got some results
} else {
//no rows
}
However note that if the query failed due to an invalid SQL or some other reason, $results will be false, so you can just do:
if(!$results) {
// Query was invalid
}
You would use mysql_num_rows() for this.
If mysql_query() returns FALSEit means there was an actaul problem with the query operation, not that there were no rows returned.
The flow goes something like this:
$query = "SELECT * FROM wherever";
if (!$result = mysql_query($query)) {
// mysql_error() gives a human readable string that explains what went wrong
// You should **never** show it in a production environment!
die('MySQL Error: '.mysql_error());
}
if (!mysql_num_rows($result)) {
// There were no results
} else {
// There were some results
}
This is only true for queries that return data (SELECT, DESCRIBE etc) - queries that just perform an action (INSERT, UPDATE, DELETE etc) will always return TRUE if the action was successful, or FALSE if it failed.
From the manual:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
If there are no records to return, mysql_num_rows($resultHandle) would return 0 (zero)
No, mysql_query will return a resource (not FALSE) also if your SELECT query do not return any rows. To check if no rows have been returned, you can use a bounch of functions:
http://www.php.net/manual/en/function.mysql-num-rows.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
...
Manual
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
To check if it's success, it might be a good idea to use isset or !empty:
$rs = mysql_query("select 1");
if (!empty($rs)){
//everything ran fine
}
else{
//something broken
}