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().
Related
I am having a strange issue with mysqli_num_rows. Searching for this issue, I've only found people having issues where NULL is returned no matter what. I also checked the official documentation for the function, and it says it returns an integer of the number of rows returned by the query. Whenever my query returns 1 row (it never should return more), it behaves as I expect. When the query returns 0 rows, I expect the function to return 0, but it returns NULL. Why doesn't it return 0?
I know that my database connection is good and my query works correctly, because when I look for a record that's in the database, I get an integer back. I just can't figure out why this is returning NULL rather than 0.
function getArtistID($name) {
global $conn;
$query = "SELECT artist_id FROM artist WHERE artist_name LIKE '${name}'";
$result = mysqli_query($conn, $query);
if ($result->num_rows) {
$row = mysqli_fetch_assoc($result);
return $row['artist_id'];
} else {
return 0;
}
}
Here's some code that I used to reproduce a case where num_rows seems to be NULL:
<?php
error_reporting(E_ALL);
$conn = new mysqli('127.0.0.1', 'root', null, 'test');
$sql = "SELECT * FROM dual";
$result = $conn->query($sql);
if ($result === false) {
print "Error: {$conn->error}\n";
}
$n = $result->num_rows;
echo "Dump the num_rows property: ";
var_dump($n);
Output:
Error: No tables used
Notice: Trying to get property of non-object in /Users/bkarwin/Documents/SO/my.php on line 14
Dump the num_rows property: NULL
The notice is because it's invalid to access an object-oriented property of a variable that is not an object. This is a frequent source of confusion for PHP developers, and it's a byproduct of the fact that PHP is a loosely typed language, and functions like query() can return either a result object, or a boolean scalar.
The query() function actually returned a false as $result because of some error. In my code, I checked for this error, and you didn't.
When you run mysqli::query() or mysqli::prepare() or mysqli_stmt::execute(), you must check for error conditions every time.
Something about your query caused an error. It's up to you to check for the error and report it.
Update: I edited some text above to make the explanation better, but it might make some comments below seem out of place.
I just can't figure out why this is returning NULL rather than 0.
We can only guess without seeing the log output; but, it is likely the return value is null because it raised an error instead.
You need to ensure that errors are handled when calling a function, before attempting to use the return value.
I get the mysql result using
$back = mysql_result($query, 0);
but when nothing is found, I get this error:
Warning: mysql_result() [<a href='function.mysql-result'>function.mysql-result</a>]: Unable to jump to row 0 on MySQL result index 2 in
I still get the error even if I use something like if (!empty($back))
How can I avoid the error? Any alternative methods are welcome
$sql = 'some query...';
$result = mysql_query($q);
if($result === false){
throw new Exception(mysql_error($connection));
}
if (mysql_num_rows($result) > 0) {
//Process Result
$back = mysql_result($query, 0);
} else {
// empty Result Set
}
Note the check on (! $result) -- if your $result is a boolean, it's certainly false, and it means there was a database error, meaning error is your query
Your error is caused by the fact that the query returned no rows - e.g. nothing matched.
I would do the mysql_query() first and check if anything was returned (if $result) before calling mysql_result.
BTW you should be using mysqli_query, etc. these days the earlier version is insecure...
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 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
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
}