How to tell if a resource is null? - php

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
}

Related

mySQL returns result even though the database is empty

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...

how to transform a function from mysql into mysqli

hello i would like to transform a mysql-function into a mysqli version. this function is for checking if an user exists or not. so i'm new to functions and even to mysqli. thats why i'm having problems while transforming it.
the mysql-version is:
function a($uname){
return (mysql_result(mysql_query("SELECT COUNT (`a`) FROM `table_1` WHERE `a`='$uname'"), 0) == 1) ? true : false;
}
the mysqli-version i thought would be:
function a($uname){
return (mysqli_num_rows(mysqli->query("SELECT COUNT (`a`) FROM `table_1` WHERE `a`='$uname'"), 0) == 1) ? true : false;
}
i know that there is no mysql_result anymore. i decided to use mysqli_num_rows. but this function does not work and i have no clue why. error_reporting is enabled but when calling the page, i will get a blank page with no error messages?!
so if there is someone who could help me out i really would appreciate.
thanks alot.
You need a helper function to put all dirty mysqli internals behind the scenes.
Like safemysql. It can mimic mysql_result as well:
function a($uname){
global $db; // with mysqi you have to connect once and then use this connection
return (bool)$db->getOne("SELECT COUNT (1) FROM table_1 WHERE a=?s"), $uname);
}
and can solve dozens of similar issues.
Freely from the documentation:
mysqli->query returns either a mysqli_result object for queries, which actually return some results, 'false' for failed queries and 'true' for all other queries (if successful).
You will not know anything about the result of your query, unless you check the result more thoroughly.
Try something like this: (This assumes that the connection has been successfully established, and that $uname has been properly escaped.)
function a($uname) {
$found = false;
$result = mysqli->query("SELECT `a` FROM `table_1` WHERE `a`='$uname'");
if($result) {
//We used a 'SELECT' query and the query was successful. That means, we now have a mysqli_result object.
$found = ($result->num_rows == 1); //Determines, if something was actually found or not.
$result->close(); //Frees some ressources. Not necessary, but doesn't hurt either.
} else { //The query failed, as such we have nothing to evaluate.
die("Queryerror: ".mysqli->error);
}
return $found;
}
I changed the query parameter from 'COUNT' to 'a', because otherwise 'num_rows' will ALWAYS return 1, even if the actual count is '0'. This way, it returns the number of matched rows, essentially return '0' for 'no match' or '1' for 'match'.

mysqli_query - return values

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.

Return a JSON string if mySQL query returns true

I have a PHP code, that will run a Select query to check if a particular personName is present. If it is present we should return a JSON stating so, and if not present we should send a JSON response stating the same.
My code so far;
$rst= mysql_query("select* from Person
where personname='Labby'");
while($r= mysql_fetch_array($rst) ){
// Now what ??
}
// How do i know if $rst= mysql_query("select* from Person
where personname='Labby'"); , returned true or false ? and depending on that create a JSON response. How can i do this ?
Either switch your query to use COUNT(*) and retrieve the value, or use mysql_num_rows() (or the mysqli or PDO equivalent).
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
from http://php.net/manual/en/function.mysql-query.php:
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
Before handling the fetch, you should test if $rst is NULL first.
if($rst)
while($r = mysql_fetch_array)
Mysql_query documentation :
Return Values
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.
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query.
The trick here is to realize that $r will be false if it can't find anything, which means that the loop will exit (or never start) if mysql can't find what you're looking for.
You can do something like:
$rst= mysql_query("select* from Person
where personname='Labby'");
$return = array();
while($r= mysql_fetch_array($rst) ){
$return[] = $r;
}
if (count($return) > 0) {
echo json_encode($return);
}
else {
echo '{"success": false}'
}
obviously you'll want to adjust the "true" and "false" return values to something that makes sense for your app

Checking for valid MySQL result resource

I have this code:
$rows = array();
$res = mysql_query($someQuery);
if(!mysql_errno())
while($row = mysql_fetch_assoc($res))
$rows[] = $row;
$someQuery is an arbitrary query that I write in to a form. The mysql_errno catches the case when I write a mysql query with errors in it. But, I just discovered that when I do a "Delete from table_name" query, it of course is not an error, but at the same time the mysql_fetch_assoc fails with a "Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /blah/blah/file.php on line x".
I've tried to look for it in the manual (maybe I'm just blind...) but is there a function I can use to check if $res is a valid MySQL result resource or not?
if ($res) should work fine to check if it's a resource. is_resource() will determine if its a valid resource at all.
You could also check mysql_affected_rows to try to determine if it's an INSERT/UPDATE/etc
Along with is_resource() you can use get_resource_type() to check whether it is a MySQL resource.
$res_type = is_resource($res) ? get_resource_type($res) : gettype($res);
if(strpos($res_type, 'mysql') === false) {
echo 'Invalid resource type: ' . $res_type;
}
get_resource_type() may return "mysql link" or "mysql link persistent" depending on your connection type.
Check http://www.lampdocs.com/blog/2010/10/how-to-check-that-a-php-variable-is-a-mysql-resource/ for the solution. Hope this helps.
mysql_query() returns true or false so you can check it this way:
if($res) {
// The query succeeded.
}
Perhaps just change the condition to:
if(!mysql_errno() && #mysql_num_rows($res) > 0)
The conditional will fail if there's no rows, and # will suppress the warning.
If you INSERT, UPDATE, DELETE or DROP via mysql_query then it will only return true or false (depending on success of operation).
I'm not sure what you are expecting the resource to contain in this instance?
If you need the number of affected rows, you can use mysql_affected_rows().

Categories