How to fetch all in assoc array from a prepared statement? - php

I'm trying this code:
if ($result = $this->mysqli->prepare("SELECT * FROM `mytable` WHERE `rows1`=?"))
{
$result->bind_param("i",$id);
$result->execute();
while ($data = $result->fetch_assoc())
{
$statistic[] = $data;
}
echo "<pre>";
var_dump($statistic);
echo "</pre>";
}
but it's throwing the following error
[Fri Jun 15 12:13:11 2012] [error] [client 127.0.0.1] PHP Fatal error:
Call to undefined method mysqli_stmt::fetch_assoc() in [myfile.php]
And also I've tried:
if ($result = $this->mysqli->prepare("SELECT * FROM `mytable` WHERE `rows1`=?"))
{
$result->bind_param("i",$id);
$rows = $result->execute();
while ($data = $rows->fetch_assoc())
{
$statistic[] = $data;
}
echo "<pre>";
var_dump($statistic);
echo "</pre>";
}
that makes this:
[Fri Jun 15 12:22:59 2012] [error] [client 127.0.0.1] PHP Fatal error:
Call to a member function fetch_assoc() on a non-object in
[myfile.php]
What else I can do for getting result or what I doing wrong? I need the assoc array from DB looking like $data[0]["id"] = 1

In fact you can do this quite easily, you just can't do it with the mysqli_stmt object, you have to extract the underlying mysqli_result, you can do this by simply calling mysqli_stmt::get_result(). Note: this requires the mysqlnd (MySQL Native Driver) extension which may not always be available.
However, the point below about recommending PDO over MySQLi still stands, and this is a prime example of why: the MySQLi userland API makes no sense. It has taken me several years of intermittently working with MySQLi for me to discover the mechanism outlined above. Now, I'll admit that separating the statement and result-set concepts does make sense, but in that case why does a statement have a fetch() method? Food for thought (if you're still sitting on the fence between MySQLi and PDO).
For completeness, here's a code sample based (loosely) on the original code in the question:
// Create a statement
$query = "
SELECT *
FROM `mytable`
WHERE `rows1` = ?
";
$stmt = $this->mysqli->prepare($query);
// Bind params and execute
$stmt->bind_param("i", $id);
// Extract result set and loop rows
$result = $stmt->get_result();
while ($data = $result->fetch_assoc())
{
$statistic[] = $data;
}
// Proof that it's working
echo "<pre>";
var_dump($statistic);
echo "</pre>";

You can do:
$stmt = $this->mysqli->prepare("SELECT * FROM `mytable` WHERE `rows1`=?");
$stmt->bind_param("i",$id);
$stmt->execute();
$result = $stmt->get_result();
$statistic = $result->fetch_all(MYSQLI_ASSOC);
$statistic contains all the result in a 2-dimensional array.
*It should be noted that this mysqli_fetch_all() function only works with the mysqlnd package.
http://php.net/manual/en/mysqli-result.fetch-all.php

I don't like Mysqli, but you can do it like this on prepare.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('hostAddress', 'username', 'password', 'databaseName');
$db->set_charset('utf8mb4');
$userID = 2;
$stmt = $db->prepare("SELECT * FROM users WHERE ID = ?");
$stmt->bind_param("i", $userID);
// because the variable is bound by reference you can assign the value after binding, too
//$userID = 2;
$stmt->execute();
if you want result;
$result = $stmt->get_result();
$user = $result->fetch_array(MYSQLI_ASSOC); //one row
or multiple row
$users = $result->fetch_all(MYSQLI_ASSOC);

With a prepared statement you don't need an array but you are free to use it.
Use the bind_result method of mysqli_stmt and you won't have any trouble.
In bind_result you defined the variables where the values of the columns should be stored in the same order as you request them from the database. You can use native variables or array keys to do so. see php docs mysqli_stmt::bind_result
You ask what's wrong with your code it is the misuse of $result->execute.
$result->execute() returns a boolean and not an instance mysqli_result as expected by you. see php docs mysqli_stmt::execute
Let's assume your database table `mytable` has the following columns: id (int), field1 (varchar), field2 (date)
Then the code would look like this:
// Initialize the array with some default values if you really want to use an array
$data = array('id'=>0,'field1'=>'','field2'=>'');
/* I recommend to explicitly define which columns you want to retrieve so you don't have to rely that the columns in the database are set in the desired order and on otherhand it doesn't matter if the database table has more columns that you want to retrieve, the code will still work as long as the columns with this names exist.*/
if ($result = $this->mysqli->prepare("SELECT `id`,`field1`,`field2` FROM `mytable` WHERE `rows1`=?"))
{
$result->bind_param("i",$id);
$result->bind_result("iss", $data['id'], $data['field1'], $data['field2']);
$result->execute();
while($result->fetch())
{
$statistic[] = $data;
}
echo "<pre>";
var_dump($statistic);
echo "</pre>";
}

Related

Will overriding the variable holding a prepared statement close the statement?

Some people recommends calling close() on a prepared statement when I am done with the result of a query.
I often reuse the same variable name for the prepared statement, so I was wondering if overriding the variable automatically calls close() on the prepared statement ?
Example of how I currently do it (The SQL is made up for the examples):
// Fetch the requested user
$stmt = $mysqli->prepare("SELECT * FROM user WHERE id = ?");
$stmt->bind_param("i", $_GET['userid']);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
// Fetch all posts associated with the user
$stmt = $mysqli->prepare("SELECT * FROM posts WHERE user_id = ?");
$stmt->bind_param("i", $user['id']);
$stmt->execute();
$result = $stmt->get_result();
$posts = array();
while ($row = $result->fetch_assoc()) {
$posts[] = $row;
}
Should I call $stmt->close(); between fetching the user and fetching the posts or is it done when I override $stmt by calling $stmt = $mysqli->prepare(...); ?
Yes, most of the time, because PHP will try to clean up objects which have no reference as soon as possible. That means that once you overwrite it, there will be no more references to the old object and PHP will clean it up. Part of cleaning up mysqli_stmt object involves closing the statement.
But the reason why some people recommend calling $stmt->close() explicitely is to avoid errors such as this:
mysqli_sql_exception: Commands out of sync; you can't run this command now in ...
This error happens when you have not fetched all results from MySQL and you try to create a new statement by calling prepare or query. MySQL will not let you execute anything else until you fetch all remaining rows. This is usually achieved with get_result() or store_result(). If you always fetch the results in their entirety then you really don't need to worry much about when exactly the statement gets closed. Let PHP take care of it for you.
The best course of action is to avoid using mysqli functions directly. You should write some simple function which will encapsulate all the mysqli functionality so that you never have to worry about this low-level stuff. A sample function could look like this:
function safeQuery(\mysqli $db, string $sql, array $params = []): ?array {
$stmt = $db->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;
}
$result = safeQuery($mysqli, 'SELECT * FROM user WHERE id = ?', [$_GET['userid']]);
if ($result) {
$user = $result[0];
$posts = safeQuery($mysqli, 'SELECT * FROM posts WHERE user_id = ?', [$user['id']]);
foreach ($posts as $post) {
}
}

Get only one Jsonobject reponse while there are two match data?

I wrote the PHP code below to get multiple JSON objects from my database:
<?php
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
$rowOfDate = $result->fetch_assoc();
echo json_encode($rowOfDate);
I expect to get two JSON objects when I run the PHP file like below because I have two month 11 data matching in My MySQL:
[{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"},{"account":"Fu","ssid":"Fu","date":"2019-11-21 00:00:00"}]
But I only get one JSON object like below:
{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"}
How to solve the problem?
You need to fetch each row in your result. You're only calling fetch_assoc() once in your code. You need to either loop until fetch_assoc() returns false, or use fetch_all() (which is supported only by the mysqlnd driver.)
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
/*** either this ****/
while($row = $result->fetch_assoc()) {
$rowOfDate[] = $row;
}
/*** or this, if it's supported ***/
$rowOfDate = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($rowOfDate);
The best solution, though, will involve changing the database API you're using. Mysqli is not very user friendly, and was written as a low-level one-to-one mapping of MySQL's C API. Even using PDO, which is PHP's other built-in database API, will make your code much easier to work with. Here's how that would look, including a parameterized query for safety:
$month = 11;
$db = new PDO("mysql:host=localhost;dbname=Fubon", "root", "of course you have a password");
$stmt = $db->prepare("SELECT * FROM clockindata WHERE MONTH(`date`) = ?");
$stmt->execute([$month]);
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// if your script is outputting JSON, set the MIME type appropriately
header("Content-Type: application/json");
echo json_encode($data);
Especially when you're using parameters in your query (which you already are, of course, right?) PDO becomes far easier to use than Mysqli.

PHP Fatal error: Call to undefined method mysqli_stmt::get_result() [duplicate]

Here's my code:
include 'conn.php';
$conn = new Connection();
$query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?';
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('sss', $_POST['EmailID'], $_POST['SLA'], $_POST['Password']);
$stmt->execute();
$result = $stmt->get_result();
I get the error on last line as: Call to undefined method mysqli_stmt::get_result()
Here is the code for conn.php:
define('SERVER', 'localhost');
define('USER', 'root');
define('PASS', 'xxxx');
define('DB', 'xxxx');
class Connection{
/**
* #var Resource
*/
var $mysqli = null;
function __construct(){
try{
if(!$this->mysqli){
$this->mysqli = new MySQLi(SERVER, USER, PASS, DB);
if(!$this->mysqli)
throw new Exception('Could not create connection using MySQLi', 'NO_CONNECTION');
}
}
catch(Exception $ex){
echo "ERROR: ".$e->getMessage();
}
}
}
If I write this line:
if(!stmt) echo 'Statement prepared'; else echo 'Statement NOT prepared';
It prints 'Statement NOT prepared'. If I run the query directly in the IDE replacing ? marks with values, it works fine. Please note that $conn object works fine in other queries in the project.
Any help please.......
Please read the user notes for this method:
http://php.net/manual/en/mysqli-stmt.get-result.php
It requires the mysqlnd driver... If it isn't installed on your webspace you will have to work with bind_result() & fetch()!
With PHP version 7.2 I just used nd_mysqli instead of mysqli and it worked as expected.
Steps to enable it into godaddy hosting server-
Login to cpanel.
Click on "Select PHP version".
As provided the snapshot of the latest configurations uncheck "mysqli" and enable "nd_mysqli".
So if the MySQL Native Driver (mysqlnd) driver is not available, and therefore using bind_result and fetch instead of get_result, the code becomes:
include 'conn.php';
$conn = new Connection();
$query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?';
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('sss', $_POST['EmailID'], $_POST['SLA'], $_POST['Password']);
$stmt->execute();
$stmt->bind_result($EmailVerified, $Blocked);
while ($stmt->fetch())
{
/* Use $EmailVerified and $Blocked */
}
$stmt->close();
$conn->mysqli->close();
Your system is missing the mysqlnd driver!
If you are able to install new packages on your (Debian/Ubuntu-based) server, install the driver:
sudo apt-get install php5-mysqlnd
and then restart your web server:
sudo /etc/init.d/apache2 restart
for those searching for an alternative to $result = $stmt->get_result() I've made this function which allows you to mimic the $result->fetch_assoc() but using directly the stmt object:
function fetchAssocStatement($stmt)
{
if($stmt->num_rows>0)
{
$result = array();
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$result[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
if($stmt->fetch())
return $result;
}
return null;
}
as you can see it creates an array and fetches it with the row data, since it uses $stmt->fetch() internally, you can call it just as you would call mysqli_result::fetch_assoc (just be sure that the $stmt object is open and result is stored):
//mysqliConnection is your mysqli connection object
$stmt = $mysqli_connection->prepare($query);
$stmt->execute();
$stmt->store_result();
while($assoc_array = fetchAssocStatement($stmt))
{
//do your magic
}
I know this was already answered as to what the actual problem is, however I want to offer a simple workaround.
I wanted to use the get_results() method however I didn't have the driver, and I'm not somewhere I can get that added. So, before I called
$stmt->bind_results($var1,$var2,$var3,$var4...etc);
I created an empty array, and then just bound the results as keys in that array:
$result = array();
$stmt->bind_results($result['var1'],$result['var2'],$result['var3'],$result['var4']...etc);
so that those results could easily be passed into methods or cast to an object for further use.
Hope this helps anyone who's looking to do something similar.
I was getting this same error on my server - PHP 7.0 with the mysqlnd extension already enabled.
Solution was for me (thanks to this page) was to deselect the mysqli extension and select nd_mysqli instead.
NB - You may be able to access the extensions selector in your cPanel. (I access mine via the Select PHP Version option.)
Here is my alternative. It is object-oriented and is more like mysql/mysqli things.
class MMySqliStmt{
private $stmt;
private $row;
public function __construct($stmt){
$this->stmt = $stmt;
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$this->row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params) or die('Sql Error');
}
public function fetch_array(){
if($this->stmt->fetch()){
$result = array();
foreach($this->row as $k => $v){
$result[$k] = $v;
}
return $result;
}else{
return false;
}
}
public function free(){
$this->stmt->close();
}
}
Usage:
$stmt = $conn->prepare($str);
//...bind_param... and so on
if(!$stmt->execute())die('Mysql Query(Execute) Error : '.$str);
$result = new MMySqliStmt($stmt);
while($row = $result->fetch_array()){
array_push($arr, $row);
//for example, use $row['id']
}
$result->free();
//for example, use the $arr
I realize that it's been a while since there has been any new activity on this question. But, as other posters have commented - get_result() is now only available in PHP by installing the MySQL native driver (mysqlnd), and in some cases, it may not be possible or desirable to install mysqlnd. So, I thought it would be helpful to post this answer with info on how get the functionality that get_result() offers - without using get_result().
get_result() is/was often combined with fetch_array() to loop through a result set and store the values from each row of the result set in a numerically-indexed or associative array. For example, the code below uses get_result() with fetch_array() to loop through a result set, storing the values from each row in the numerically-indexed $data[] array:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$result = $stmt->get_result();
while($data = $result->fetch_array(MYSQLI_NUM)) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
However, if get_result() is not available (because mysqlnd is not installed), then this leads to the problem of how to store the values from each row of a result set in an array, without using get_result(). Or, how to migrate legacy code that uses get_result() to run without it (e.g. using bind_result() instead) - while impacting the rest of the code as little as possible.
It turns out that storing the values from each row in a numerically-indexed array is not so straight-forward using bind_result(). bind_result() expects a list of scalar variables (not an array). So, it takes some doing to make it store the values from each row of the result set in an array.
Of course, the code could easily be modified as follows:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$stmt->bind_result($data[0], $data[1]);
while ($stmt->fetch()) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
But, this requires us to explicitly list $data[0], $data[1], etc. individually in the call to bind_result(), which is not ideal. We want a solution that doesn't require us to have to explicitly list $data[0], $data[1], ... $data[N-1] (where N is the number of fields in the select statement) in the call to bind_results(). If we're migrating a legacy application that has a large number of queries, and each query may contain a different number of fields in the select clause, the migration will be very labor intensive and prone to error if we use a solution like the one above.
Ideally, we want a snippet of 'drop-in replacement' code - to replace just the line containing the get_result() function and the while() loop on the next line. The replacement code should have the same function as the code that it's replacing, without affecting any of the lines before, or any of the lines after - including the lines inside the while() loop. Ideally we want the replacement code to be as compact as possible, and we don't want to have to taylor the replacement code based on the number of fields in the select clause of the query.
Searching on the internet, I found a number of solutions that use bind_param() with call_user_func_array()
(for example, Dynamically bind mysqli_stmt parameters and then bind result (PHP)), but most solutions that I found eventually lead to the results being stored in an associative array, not a numerically-indexed array, and many of these solutions were not as compact as I would like and/or were not suited as 'drop-in replacements'. However, from the examples that I found, I was able to cobble together this solution, which fits the bill:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$data=array();
for ($i=0;$i<$mysqli->field_count;$i++) {
$var = $i;
$$var = null;
$data[$var] = &$$var;
}
call_user_func_array(array($stmt,'bind_result'), $data);
while ($stmt->fetch()) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
Of course, the for() loop can be collapsed into one line to make it more compact.
I hope this helps anyone who is looking for a solution using bind_result() to store the values from each row in a numerically-indexed array and/or looking for a way to migrate legacy code using get_result(). Comments welcome.
I have written two simple functions that give the same functionality as $stmt->get_result();, but they don't require the mysqlnd driver.
You simply replace
$result = $stmt->get_result(); with $fields = bindAll($stmt);
and
$row= $stmt->get_result(); with $row = fetchRowAssoc($stmt, $fields);.
(To get the numbers of returned rows you can use $stmt->num_rows.)
You just have to place these two functions I have written somewhere in your PHP Script. (for example right at the bottom)
function bindAll($stmt) {
$meta = $stmt->result_metadata();
$fields = array();
$fieldRefs = array();
while ($field = $meta->fetch_field())
{
$fields[$field->name] = "";
$fieldRefs[] = &$fields[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $fieldRefs);
$stmt->store_result();
//var_dump($fields);
return $fields;
}
function fetchRowAssoc($stmt, &$fields) {
if ($stmt->fetch()) {
return $fields;
}
return false;
}
How it works:
My code uses the $stmt->result_metadata(); function to figure out how many and which fields are returned and then automatically binds the fetched results to pre-created references. Works like a charm!

Call to undefined method mysqli_stmt::get_result() for login [duplicate]

Here's my code:
include 'conn.php';
$conn = new Connection();
$query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?';
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('sss', $_POST['EmailID'], $_POST['SLA'], $_POST['Password']);
$stmt->execute();
$result = $stmt->get_result();
I get the error on last line as: Call to undefined method mysqli_stmt::get_result()
Here is the code for conn.php:
define('SERVER', 'localhost');
define('USER', 'root');
define('PASS', 'xxxx');
define('DB', 'xxxx');
class Connection{
/**
* #var Resource
*/
var $mysqli = null;
function __construct(){
try{
if(!$this->mysqli){
$this->mysqli = new MySQLi(SERVER, USER, PASS, DB);
if(!$this->mysqli)
throw new Exception('Could not create connection using MySQLi', 'NO_CONNECTION');
}
}
catch(Exception $ex){
echo "ERROR: ".$e->getMessage();
}
}
}
If I write this line:
if(!stmt) echo 'Statement prepared'; else echo 'Statement NOT prepared';
It prints 'Statement NOT prepared'. If I run the query directly in the IDE replacing ? marks with values, it works fine. Please note that $conn object works fine in other queries in the project.
Any help please.......
Please read the user notes for this method:
http://php.net/manual/en/mysqli-stmt.get-result.php
It requires the mysqlnd driver... If it isn't installed on your webspace you will have to work with bind_result() & fetch()!
With PHP version 7.2 I just used nd_mysqli instead of mysqli and it worked as expected.
Steps to enable it into godaddy hosting server-
Login to cpanel.
Click on "Select PHP version".
As provided the snapshot of the latest configurations uncheck "mysqli" and enable "nd_mysqli".
So if the MySQL Native Driver (mysqlnd) driver is not available, and therefore using bind_result and fetch instead of get_result, the code becomes:
include 'conn.php';
$conn = new Connection();
$query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?';
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('sss', $_POST['EmailID'], $_POST['SLA'], $_POST['Password']);
$stmt->execute();
$stmt->bind_result($EmailVerified, $Blocked);
while ($stmt->fetch())
{
/* Use $EmailVerified and $Blocked */
}
$stmt->close();
$conn->mysqli->close();
Your system is missing the mysqlnd driver!
If you are able to install new packages on your (Debian/Ubuntu-based) server, install the driver:
sudo apt-get install php5-mysqlnd
and then restart your web server:
sudo /etc/init.d/apache2 restart
for those searching for an alternative to $result = $stmt->get_result() I've made this function which allows you to mimic the $result->fetch_assoc() but using directly the stmt object:
function fetchAssocStatement($stmt)
{
if($stmt->num_rows>0)
{
$result = array();
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$result[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
if($stmt->fetch())
return $result;
}
return null;
}
as you can see it creates an array and fetches it with the row data, since it uses $stmt->fetch() internally, you can call it just as you would call mysqli_result::fetch_assoc (just be sure that the $stmt object is open and result is stored):
//mysqliConnection is your mysqli connection object
$stmt = $mysqli_connection->prepare($query);
$stmt->execute();
$stmt->store_result();
while($assoc_array = fetchAssocStatement($stmt))
{
//do your magic
}
I know this was already answered as to what the actual problem is, however I want to offer a simple workaround.
I wanted to use the get_results() method however I didn't have the driver, and I'm not somewhere I can get that added. So, before I called
$stmt->bind_results($var1,$var2,$var3,$var4...etc);
I created an empty array, and then just bound the results as keys in that array:
$result = array();
$stmt->bind_results($result['var1'],$result['var2'],$result['var3'],$result['var4']...etc);
so that those results could easily be passed into methods or cast to an object for further use.
Hope this helps anyone who's looking to do something similar.
I was getting this same error on my server - PHP 7.0 with the mysqlnd extension already enabled.
Solution was for me (thanks to this page) was to deselect the mysqli extension and select nd_mysqli instead.
NB - You may be able to access the extensions selector in your cPanel. (I access mine via the Select PHP Version option.)
Here is my alternative. It is object-oriented and is more like mysql/mysqli things.
class MMySqliStmt{
private $stmt;
private $row;
public function __construct($stmt){
$this->stmt = $stmt;
$md = $stmt->result_metadata();
$params = array();
while($field = $md->fetch_field()) {
$params[] = &$this->row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params) or die('Sql Error');
}
public function fetch_array(){
if($this->stmt->fetch()){
$result = array();
foreach($this->row as $k => $v){
$result[$k] = $v;
}
return $result;
}else{
return false;
}
}
public function free(){
$this->stmt->close();
}
}
Usage:
$stmt = $conn->prepare($str);
//...bind_param... and so on
if(!$stmt->execute())die('Mysql Query(Execute) Error : '.$str);
$result = new MMySqliStmt($stmt);
while($row = $result->fetch_array()){
array_push($arr, $row);
//for example, use $row['id']
}
$result->free();
//for example, use the $arr
I realize that it's been a while since there has been any new activity on this question. But, as other posters have commented - get_result() is now only available in PHP by installing the MySQL native driver (mysqlnd), and in some cases, it may not be possible or desirable to install mysqlnd. So, I thought it would be helpful to post this answer with info on how get the functionality that get_result() offers - without using get_result().
get_result() is/was often combined with fetch_array() to loop through a result set and store the values from each row of the result set in a numerically-indexed or associative array. For example, the code below uses get_result() with fetch_array() to loop through a result set, storing the values from each row in the numerically-indexed $data[] array:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$result = $stmt->get_result();
while($data = $result->fetch_array(MYSQLI_NUM)) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
However, if get_result() is not available (because mysqlnd is not installed), then this leads to the problem of how to store the values from each row of a result set in an array, without using get_result(). Or, how to migrate legacy code that uses get_result() to run without it (e.g. using bind_result() instead) - while impacting the rest of the code as little as possible.
It turns out that storing the values from each row in a numerically-indexed array is not so straight-forward using bind_result(). bind_result() expects a list of scalar variables (not an array). So, it takes some doing to make it store the values from each row of the result set in an array.
Of course, the code could easily be modified as follows:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$stmt->bind_result($data[0], $data[1]);
while ($stmt->fetch()) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
But, this requires us to explicitly list $data[0], $data[1], etc. individually in the call to bind_result(), which is not ideal. We want a solution that doesn't require us to have to explicitly list $data[0], $data[1], ... $data[N-1] (where N is the number of fields in the select statement) in the call to bind_results(). If we're migrating a legacy application that has a large number of queries, and each query may contain a different number of fields in the select clause, the migration will be very labor intensive and prone to error if we use a solution like the one above.
Ideally, we want a snippet of 'drop-in replacement' code - to replace just the line containing the get_result() function and the while() loop on the next line. The replacement code should have the same function as the code that it's replacing, without affecting any of the lines before, or any of the lines after - including the lines inside the while() loop. Ideally we want the replacement code to be as compact as possible, and we don't want to have to taylor the replacement code based on the number of fields in the select clause of the query.
Searching on the internet, I found a number of solutions that use bind_param() with call_user_func_array()
(for example, Dynamically bind mysqli_stmt parameters and then bind result (PHP)), but most solutions that I found eventually lead to the results being stored in an associative array, not a numerically-indexed array, and many of these solutions were not as compact as I would like and/or were not suited as 'drop-in replacements'. However, from the examples that I found, I was able to cobble together this solution, which fits the bill:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$data=array();
for ($i=0;$i<$mysqli->field_count;$i++) {
$var = $i;
$$var = null;
$data[$var] = &$$var;
}
call_user_func_array(array($stmt,'bind_result'), $data);
while ($stmt->fetch()) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
Of course, the for() loop can be collapsed into one line to make it more compact.
I hope this helps anyone who is looking for a solution using bind_result() to store the values from each row in a numerically-indexed array and/or looking for a way to migrate legacy code using get_result(). Comments welcome.
I have written two simple functions that give the same functionality as $stmt->get_result();, but they don't require the mysqlnd driver.
You simply replace
$result = $stmt->get_result(); with $fields = bindAll($stmt);
and
$row= $stmt->get_result(); with $row = fetchRowAssoc($stmt, $fields);.
(To get the numbers of returned rows you can use $stmt->num_rows.)
You just have to place these two functions I have written somewhere in your PHP Script. (for example right at the bottom)
function bindAll($stmt) {
$meta = $stmt->result_metadata();
$fields = array();
$fieldRefs = array();
while ($field = $meta->fetch_field())
{
$fields[$field->name] = "";
$fieldRefs[] = &$fields[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $fieldRefs);
$stmt->store_result();
//var_dump($fields);
return $fields;
}
function fetchRowAssoc($stmt, &$fields) {
if ($stmt->fetch()) {
return $fields;
}
return false;
}
How it works:
My code uses the $stmt->result_metadata(); function to figure out how many and which fields are returned and then automatically binds the fetched results to pre-created references. Works like a charm!

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';
}

Categories