How to know if MySQL returns 0 - php

When I run this query `
SELECT id FROM bckoff WHERE left
= 3;
`
in phpmyAdmin, I get the correct response
MySQL returned an empty result set
(i.e. zero rows).
However, when I run the same query through my PHP code using mysql_query('the above query').. then I get "Resource ID#5" or "Resource ID#6" and so on..
How do I get the empty result set (or zero rows) in PHP ?

mysql_num_rows is the answer. This function returns the number of rows affected by a executed query.
$query = "SELECT id FROM bckoff WHERE left = 3";
$result = mysql_query($query);
echo mysql_num_rows($result);
When you execute mysql_query($query) it executes the query and puts it in a resource. This resource can be read by different mysql-functions (like mysql_num_rows). For a complete overview of all MySQL functions have a look at http://nl.php.net/manual/en/ref.mysql.php
Note: Extension used in above code is deprecated as of PHP 5.5.0, Use MySQLi or PDO_MySQL extension.
So instead of mysql_num_rows use mysqli_num_rows()

You can use mysql_num_rows function as:
$result = mysql_query("SELECT id FROM bckoff WHERE left = 3");
$num_rows = mysql_num_rows($result);
// $num_rows will be 0.

You need to use a mysql_fetch_* function to retrieve the results. Look here
Mysql Fetch Functions

There is a mysql_num_rows function that you can call on the $result returned by mysql_query("SELECT ...").
You might look into the MySQLi extension instead. It's a big improvement over the MySQL driver, and allows you to use prepared statements and bind parameters among other things, and I find it much more comfortable to use. You can look at the examples on the documentation page for num_rows.

Related

how to get the count of row values in php pdo

There are many conflicting statements around, what is the best way to row count using PDO in PHP? Before using PDO I just simply used mysql_num_rows.
fetchAll is something I won't want as I may sometimes be dealing with large datasets, so not good for my use.
Any suggestions?
In Mysql $stmt->rowCount(); doesnt work. Try this
$nRows = $pdo->query('select count(*) from yourTable')->fetchColumn();
echo 'Number of rows is = '. $nRows;
Here is an excerpt from a comment and answer regarding the same. Check it out its very resourceful.
mysql_num_rows() worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you. Refer to this anwere
So in PDO, your options are:
Use MySQL's FOUND_ROWS() function.
Use PDO's fetch_all() function to fetch all the rows into an array,
then use count() on it.
Do an extra query to SELECT COUNT(*),
https://stackoverflow.com/a/883523/2536812
Directly out form PHP Manual about PDO Statements
$stmt->rowCount();
The $stmtvalue is for exemple the return of a prepare :
$stmt = $pdo->prepare('MY PREPARED SQL QUERY');

Way to test more data without advancing pointer?

Is there a way to check end-of-file on a recordset returned from MySQL (in PHP)?
I'd like to do something like the following:
while (!mysql_eof($result) {
$row = mysql_fetch_array($result);
}
I don't want to use mysql_fetch_array() in the main loop, because I need to do further reads inside the loop and don't want the recordset current record counter updated ie. I do not want to advance the current pointer.
Write your query like
$result = mysql_query("SELECT * FROM MyTable ORDER BY id DESC LIMIT 0,1");
$row = mysql_fetch_assoc($result);
print_r($row);
And try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.
$result = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
$counter = 1;
while($counter<=$num_rows)
{
//There is still more data
//Do whatever to the current row
$counter++;
}
Hope this does it. If not, I don't know what will.
mysql_eof() is deprecated. mysql_errno() or mysql_error() may be used instead.
mysql_eof() determines whether the last row of a result set has been read.
If you acquire a result set from a successful call to mysql_store_result(), the client receives the entire set in one operation. In this case, a NULL return from mysql_fetch_row() always means the end of the result set has been reached and it is unnecessary to call mysql_eof(). When used with mysql_store_result(), mysql_eof() always returns true.
Check out : http://dev.mysql.com/doc/refman/4.1/en/mysql-eof.html for more details.

PHP MYSQL query shortcut?

If I am doing a PHP MYSQL select of a table using the where clause that will return only 1 result, is there a simpler way to do this:
$result = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
$cartrec = mysql_fetch_array($result);
Is the $cartrec = mysql_fetch_array($result); needed or could I just do:
$cartrec = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
or is there a better syntax to use?
mysql_query gets a result set (actually, a resource that refers to a result set) based on your query. This is the set of records that match your query.
mysql_fetch_array gets the first record from a result set, and returns it as an array.
So, up until you've called mysql_fetch_array, you haven't gotten the data in a usable format.
Side note: Consider using PDO
The fetch array is required, the mysql_query gets a result set (ressource), then mysql_fetch_array get's the element in the result set.
As a side note, be careful of SQL injections: http://en.wikipedia.org/wiki/SQL_injection
EDIT: Might be a bit more advanced that what you need, but it might be worth while looking into PDO: http://php.net/manual/en/book.pdo.php
Is the $cartrec = mysql_fetch_array($result); needed
Yes, otherwise you get a resource pointer not an result set (array).
or is there a better syntax to use?
Yes, MySQLi
No, but its pretty common for people to write their own function for this use case. It's usually named something like fetch_one($sqlString) or fetch_first($sqlString)
You could use this, but if the database structure were to change, it would be problematic
$row = mysql_fetch_row($result);
echo $row[0]; //column 1
echo $row[1]; //column 2
You may want to look at this http://www.php.net/manual/en/function.mysql-fetch-row.php

How do I use a MySQL user-defined function from within PHP?

Spent several hours searching for an answer without success. I've written a user-defined function in MySQL which is passed an identifier which it uses to retrieve various pieces of data, concatenate it into one string and return it. I want to call this function from my PHP page and output the result.
Unsuccessful attempts include:
1. $result = mysql_query("select functionName($id)");
2. $sql = "select functionName($id)";
$result = mysql_query($sql, $link);
3. functionName($id)
Any ideas?
1 and 2 are close, but $result is not going to contain the result of the function call. Rather, it is going to contain the result cookie from the query. You can use that cookie to get the actual data, with mysql_fetch_row(). The function call just returns a value for the select statement, just the same as "SELECT 42" or "SELECT a FROM MyTable". So to get the result you would use the same mechanism as with any other SQL query that returns results; that is, use the cookie and call mysql_fetch_row(). So your final code will look like this:
$result = mysql_query("select functionName($id)");
$row = mysql_fetch_row($result, $link);
$returnValue = $row[0];
Note that you don't want to be interpolating variables directly into an SQL string (that can be a vector for attacks). I assume, however, that this code is just for example purposes.
I had the same question and found this very useful write up from devx, particulary the part at the bottom about calling MySQL functions:
http://www.devx.com/webdev/Article/42887/0/page/2
With regards to mysqli, my code is now as follows:
$result = mysqli_query($sqlconnection,"SELECT functionName($id)");
$row = mysqli_fetch_row($result);
return $row[0];
works perfectly.

More efficient way to COUNT() MYSQL rows via PHP?

Here is how I am currently counting mysql rows in PHP:
//GET total # of results and build $start and $end for main SQL statement
$sql= 'SELECT COUNT(*) FROM savedsearches WHERE user_id=\''.mysql_real_escape_string($user_id).'\'';
$initial_query = mysql_query($sql) or die("SQL error");
$num_sql = mysql_fetch_array($initial_query);
$numrows = $num_sql[0];
mysql_free_result($initial_query);
Is there a more efficient way to do this?
No. If you want a count , you run the query you're already running.
If you need more efficiency, make sure there is an index on the user_id column
//GET total # of results and build $start and $end for main SQL statement
$sql= 'SELECT * FROM savedsearches WHERE user_id=\''.mysql_real_escape_string($user_id).'\'';
$initial_query = mysql_query($sql) or die("SQL error");
$numrows = mysql_num_rows($initial_query)
As you can see, you can run mysql_num_rows() BEFORE mysql_fetch_array. This is very useful to me, since it allows me to know before hand, weather or not I have the amount of rows I need. If you want to learn more about this function: PHP Manual: mysql_num_rows()
You mean, do it in fewer lines of code? You could put that functionality into a user-defined function and then call the function instead of using that code, but other than that, it's not going to get an awful lot terser.

Categories