num_rows: get_result vs store_result - php

The following code returns 0, even though there are 5 entries in the table categories with cat = 1.
$sql = "SELECT name FROM categories WHERE cat = ?";
$stmt = $db->prepare($sql);
$cat = 1;
$stmt->bind_param("i", $cat);
$stmt->execute();
$stmt->get_result();
echo $stmt->num_rows;
However, when I change $stmt->get_result(); to $stmt->store_result(); the output is 5. Why does get_result() not work here?
I found for instance on this answer: https://stackoverflow.com/a/8722329/2311074 that get_result() should also work.

Looks like the other answer is wrong and get_result doesn't change the state of a statement (which is quite logical, as you are asking for mysqli_result and therefore supposedly going to work with it from now on).
You see, the way you are using get_result is quite pointless. To make any point of it, you have to assign the result to a variable, which will give you the desired outcome:
$res = $stmt->get_result();
echo $res->num_rows;
Note that the num_rows property is quite useless in general. If you want to know whether your query returned any data or not, just collect the rows into array and then you use this array for the purpose.
$data = $stmt->get_result()->fetch_all();
if ($data) {
// whatever
} else {
// oops!
}
And of course you shouldn't use such a query only to count the goods available in a category. For such a purpose a count(*) query have to be used.

Related

mysqli_free_result () VS mysqli_stmt_free_result() differences and usage?

What are the differences and specific use cases of these two functions? Here's what I found:
mysqli_free_result — Frees the memory associated with a result
mysqli_stmt_free_result — Frees stored result memory for the given statement handle
An example will be nice.
These are two different functions, but you don't need to use any of them.
mysqli_free_result
mysqli_free_result() is the procedural equivalent of $result->free(). All it does is it unsets the results from the variable. The object still exists, but becomes unusable.
$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM student_detail WHERE ID=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
$result->free();
var_dump($result->fetch_assoc()); // error
It also has 2 aliases. These 4 are all the same thing:
$result->free();
$result->close();
$result->free_result();
mysqli_free_result($result);
mysqli_stmt_free_result
Does the same thing, but with the statement itself. It is the equivalent of $stmt->free_result()
$id = 1;
$stmt = $mysqli->prepare('SELECT * FROM student_detail WHERE ID=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->store_result();
$stmt->free_result();
var_dump($stmt->fetch()); // false
You can assume that if you ever find yourself needing to use any of them, then it means you have probably done something wrong.
For example, some people claim it saves memory for your server when you free the result once you are done with it. In reality you should encapsulate your database queries in such way that the mysqli_result lives only as long as you need it. Take a look at one method I have written a while ago:
public function safeQuery(string $sql, array $params = []): ?array {
$stmt = $this->prepare($sql);
if ($params) {
$stmt->bind_param(str_repeat("s", count($params)), ...$params);
}
$stmt->execute();
if ($result = $stmt->get_result()) {
return $result->fetch_all(MYSQLI_BOTH);
}
return null;
}
It executes prepared statement, gets the result, fetches the records and the mysqli_result is alive as long as it is needed and not a moment more.
They're equivalent, it depends on how you created the results in the first place.
If you use a prepared statement and then use $stmt->store_result(), you would free the results using $stmt->free_result().
If you perform an ordinary query like $result = $conn->query(...), you would free it using $result->free_result().

PHP PDO Select Query Results

This seems like it should be a very easy task, but I'm not sure it is.
I would like to use PDO to do a SELECT query, and then immediately after find out if there are any results (rows), and if so how many.
I'd like to fetch the result as an object not an array, as I like the $obj->col_name syntax, and it just feels a bit wrong to return an array just to find the above out.
$qryh = $conn->query("SELECT ...");
Then use $qryh to first find out if there are any rows, and if so how many.
Can this be done without falling back to using arrays..?
UPDATE:
I know about rowCount(), but I think it only works on UPDATE, INSERT and DELETE - my question relates to SELECT.
UPDATE 2:
I'm using SQL Server and MS Access, not MySQL, and rocount() does not work.
SOLUTION FOUND
The accepted answer lead to the solution. Here is what I found:
I was setting the PDO::ATTR_CURSOR option to PDO::CURSOR_SCROLL when creating the PDO object (new PDO(...), which returned -1 on a rowCount(). However if I set the cursor within ->prepare(... using an array (array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)) it works and returns the row count.
http://technet.microsoft.com/en-us/library/ff628154(v=sql.105).aspx
So, the example on the above link works, setting the cursor when you create the PDO object doesn't work. Also note that in the 'remarks' section on the above link, it mentions PDO::CURSOR_SCROLLABLE which doesn't for me (I get Undefined class constant 'CURSOR_SCROLLABLE').
Try this way:
$query = "select * from ...";
$stmt = $conn->prepare( $query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
print $stmt->rowCount()
Should work
$stmt = $conn->query('SELECT ...');
// number of rows:
$rows = $stmt->rowCount();
// get an array with objects:
$objects = $stmt->fetchAll();
// another way to count the results:
$rows = count($objects);
This is what I do in my database class:
$stmt = $conn->prepare('SELECT ...');
$stmt->execute();
$arrayOfObjects = $stmt->fetchALL(PDO::FETCH_OBJ);
$numberOfRows = count($arrayOfObjects);
print $numberOfRows;
By passing PDO::FETCH_OBJ each object is an stdClass meaning you can use the -> syntax.
I believe this is what you are looking for, and it just uses the PHP count() function instead of mySQL rowCount().
If you want more context, here is the DB class I use in all of my projects: https://gist.github.com/pxlsqre/9f6471220ef187343f54
You're right, PDO::rowCount does not work properly with SELECT
One workaround is to Add the count to your query
$qryh = $conn->query("SELECT COUNT(*) as numRows FROM Table");
$result = $qryh->(PDO::FETCH_OBJ);;
$count = $result->numRows;
$qryh->fetchColumn()
Returns the number of rows selected through a SELECT query

MySQLI Prepared Statement: num_rows & fetch_assoc

Below is some poorly written and heavily misunderstood PHP code with no error checking. To be honest, I'm struggling a little getting my head around the maze of PHP->MySQLi functions! Could someone please provide an example of how one would use prepared statements to collect results in an associative array whilst also getting a row count from $stmt? The code below is what I'm playing around with. I think the bit that's throwing me off is using $stmt values after store_result and then trying to collect an assoc array, and I'm not too sure why...
$mysqli = mysqli_connect($config['host'], $config['user'], $config['pass'], $config['db']);
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
$stmt->bind_param('i', $core['id']);
$result = $stmt->execute();
$stmt->store_result();
if ($stmt->num_rows >= "1") {
while($data = $result->fetch_assoc()){
//Loop through results here $data[]
}
}else{
echo "0 records found";
}
I feel a little cheeky just asking for code, but its a working demonstration of my circumstances that I feel I need to finally understand what's actually going on. Thanks a million!
I searched for a long time but never found documentation needed to respond correctly, but I did my research.
$stmt->get_result() replace $stmt->store_result() for this purpose.
So, If we see
$stmt_result = $stmt->get_result();
var_dump($stmt_result);
we get
object(mysqli_result)[3]
public 'current_field' => int 0
public 'field_count' => int 10
public 'lengths' => null
public 'num_rows' => int 8 #That we need!
public 'type' => int 0
Therefore I propose the following generic solution. (I include the bug report I use)
#Prepare stmt or reports errors
($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
#Execute stmt or reports errors
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
#Save data or reports errors
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
#Check if are rows in query
if ($stmt_result->num_rows>0) {
# Save in $row_data[] all columns of query
while($row_data = $stmt_result->fetch_assoc()) {
# Action to do
echo $row_data['my_db_column_name_or_ALIAS'];
}
} else {
# No data actions
echo 'No data here :(';
}
$stmt->close();
$result = $stmt->execute(); /* function returns a bool value */
reference : http://php.net/manual/en/mysqli-stmt.execute.php
so its just sufficient to write $stmt->execute(); for the query execution.
The basic idea is to follow the following sequence :
1. make a connection. (now while using sqli or PDO method you make connection and connect with database in a single step)
2. prepare the query template
3. bind the the parameters with the variable
4. (set the values for the variable if not set or if you wish to change the values) and then Execute your query.
5. Now fetch your data and do your work.
6. Close the connection.
/*STEP 1*/
$mysqli = mysqli_connect($servername,$usrname,$pswd,$dbname);
/*STEP 2*/
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
/*Prepares the SQL query, and returns a statement handle to be used for further operations on the statement.*/
//mysqli_prepare() returns a statement object(of class mysqli_stmt) or FALSE if an error occurred.
/* STEP 3*/
$stmt->bind_param('i', $core['id']);//Binds variables to a prepared statement as parameters
/* STEP 4*/
$result = $stmt->execute();//Executes a prepared Query
/* IF you wish to count the no. of rows only then you will require the following 2 lines */
$stmt->store_result();//Transfers a result set from a prepared statement
$count=$stmt->num_rows;
/*STEP 5*/
//The best way is to bind result, its easy and sleek
while($data = $stmt->fetch()) //use fetch() fetch_assoc() is not a member of mysqli_stmt class
{ //DO what you wish
//$data is an array, one can access the contents like $data['attributeName']
}
One must call mysqli_stmt_store_result() for (SELECT, SHOW, DESCRIBE, EXPLAIN), if one wants to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data.
It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases.
--reference: php.net/manual/en/mysqli-stmt.store-result.php
and http://www.w3schools.com/php/php_mysql_prepared_statements.asp
One must look up the above reference who are facing issue regarding this,
My answer may not be perfect, people are welcome to improve my answer...
If you would like to collect mysqli results into an associative array in PHP you can use fetch_all() method. Of course before you try to fetch the rows, you need to get the result with get_result(). execute() does not return any useful values.
For example:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($config['host'], $config['user'], $config['pass'], $config['db']);
$mysqli->set_charset('utf8mb4'); // Don't forget to set the charset!
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
$stmt->bind_param('i', $core['id']);
$stmt->execute(); // This doesn't return any useful value
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
if ($data) {
foreach ($data as $row) {
//Loop through results here
}
} else {
echo "0 records found";
}
I am not sure why would you need num_rows, you can always use the array itself to check if there are any rows. An empty array is false-ish in PHP.
Your problem here is that to do a fetch->assoc(), you need to get first a result set from a prepared statement using:
http://php.net/manual/en/mysqli-stmt.get-result.php
And guess what: this function only works if you are using MySQL native driver, or "mysqlnd". If you are not using it, you'll get the "Fatal error" message.
You can try this using the mysqli_stmt function get_result() which you can use to fetch an associated array. Note get_result returns an object of type mysqli_result.
$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows; //count number of rows in the result
// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if ($result_array = $result->fetch_assoc(MYSQLI_ASSOC)) {
//loop through the result_array fetching rows.
// $ rows is an array populated with all the rows with an associative array with column names as the key
for($j=0;$j<$num_rows;$j++)
$rows[$j]=$result->fetch_row();
var_dump($rows);
}
else{
echo 'Failed to retrieve rows';
}

MySQLi num_rows returns 0

Here's my code
$stmt = $conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare('SELECT Username, EmailVerified, Blocked FROM user WHERE Email = ? AND SLANumber = ? AND Password = ?');
$stmt->bind_param('ssb', $_POST['EmailID'], $_POST['SLANumber'], $_POST['Password']);
$stmt->execute();
$stmt->store_result();
$result = $stmt->get_result();
if($result->num_rows == 0){
echo 'No rows found';
}
else{
// Continue processing here
.....
}
The code always echoes No rows found. A day or two before, it was working fine.
As expected, running the query directly gives the desired result.
What's wrong with the code?
Don't use store_result and get_result together in the same statement.
Use store_result method with "num_rows", "bind_result" and "fetch".
For get_result method, use "affected_rows" and "fetch_array". You can still use the "num_rows" property in the income get_result method as shown below.
$stmt->execute();
// $stmt->store_result();
$result = $stmt->get_result();
if(result->num_rows == 0){
...
}
OR
$stmt->execute();
// $stmt->store_result();
$result = $stmt->get_result();
if($stmt->affected_rows == 0){
...
}
To fix your problem remove this line:
$stmt->store_result();
The problem is that you used two methods which are in conflict with each other.
$stmt->store_result();
$result = $stmt->get_result();
Both of these methods fetch the results. store_result() fetches the results internally and stores them in the statement object. I would advise to avoid this method whenever possible. It is difficult to use. get_result() fetches the results and saves them in a separate object. Once the results are fetched from MySQL, they cannot be fetched again. Use only one of these methods at a time.
In your case you first stored the results in mysqli_stmt and then fetched an empty result set into $result. $result will contain 0 rows, because all of the records have already been stored in the statement. To get the number of rows stored there use $stmt->num_rows.
Both mysqli_stmt and mysqli_result classes have the num_rows property. The key is to use the appropriate one.
num_rows is a property of mysqli_stmt, not of a result resource. So you should be doing:
$result = $stmt->get_result();
// Also check strict comparison against int 0,
// to avoid incorrect equality with boolean FALSE
if($stmt->num_rows === 0){
echo 'No rows found';
}

Why doesn't this prepare statement work in MYSQLI?

I created this code:
$statement = $db->prepare("SELECT * FROM phptech_contact");
$statement->execute();
$result = $statement->result_metadata();
$object = $result->fetch_object();
print_r( $object );
When I run it, it doesn't work. Can anybody tell me why it doesn't work?
I have 20 rows in this table so data should be returned.
From http://ch.php.net/manual/en/mysqli-stmt.result-metadata.php
Note: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().
As long as you don't need this meta data you don't need to call this method.
$statement = $db->prepare("SELECT fld1, fld2 FROM phptech_contact");
$statement->execute();
$stmt->bind_result($fld1, $fld2);
while ($stmt->fetch()) {
echo "$fld1 and $fld2<br />";
}
But I really dislike the mysqli extension. PDO is much cooler ... ;-)
$db = new PDO('...');
$stmt = $db->prepare("SELECT fld1, fld2 FROM phptech_contact");
$stmt->execute();
while ($obj = $stmt->fetchObject()) {
// ...
}
or
$objs = stmt->fetchAll(PDO::FETCH_OBJ);
if you're trying to get the rows from the database, the function you need is mysqli_stmt::fetch(), not mysqli_stmt::fetch_metadata()
You're also missing a few steps. When using prepared statements, you must specify the fields you would like to return instead of using the star wildcard, and then use mysqli_stmt::bind_result() to specify which variables the database fields should be placed in.
If you're more familiar with the original MySQL extension, prepared statements have a different process to use. If your select statement has a parameter (eg., "WHERE value=?") prepared statements are definitely recommended, but for your simple query, mysqli:query() would be sufficient, and not very different from the process of mysql_query()
I believe the problem is that mysqli_stmt::result_metadata() returns a mysqli_result object without any of the actual results — it only holds metadata.
So what you want to do is use $result = $statement->bind_result(...) and then call $result->fetch() repeatedly to get the results.
One of the comments under the bind-result() article shows how to do this for a query like yours, where you don't necessarily know all of the columns being returned.

Categories