I have a sql query and a mysqli prepared statement:
$sql = 'SELECT photographers.photographer_id, photographers.photographer_name
FROM photographers';
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_result($photographer_id, $photographer_name);
$OK = $stmt->execute();
$stmt->fetch();
}
How can I store the results in an associative array so I can loop it later and get to all the data returned by the sql string?
Oddly enough, you can't. There's simply no way to get a mysqli_result object from a mysqli_stmt instance. I've always considered this a major flaw, and would guess that this is one of the major reasons that mysqli never reached any real popularity. These days it's been pretty much superseded by PDO, which does what you want with out effort.
Edit: My answer only means that you can't do it by default. Of course you can implement it yourself, like Chris suggested. Still, I think you should use PDO instead, if it's at all possible.
A simple one that actually surprisingly works. I know it's procedural, but still:
If you cannot use the PDO extension. Or you are having trouble building your database class with prepared statements. How to use for insert update, delete and insert:
Fetch works a bit different
Now for the database class
I hope this is helpful
Try the following:
First you get the query metadata and from that obtain all the fields you've fetched (you could do this manually, but this code works for all queries rather than building by hand). The
call_user_func_array()
function calls themysqli_stmt::bind_result()
function for you on each of those parameters.After that it is just a matter of running through each row and creating an associative array for each row and adding that to an array resulting in all the results.
I came across this discussion in order to find a solution for getting data from MySQLi prepared statements without the mysqlnd. I have been developing a class for handling prepared statements with MySQLi in a handy way. Please, take a look to the code, or simply use it (see an example of usage at the end of the piece of code) to fastly write prepared statements and get its results.
Update: Since PHP 5.3.0 you can get a mysqli_result object that provides a fetch_array method.
Documentation: http://php.net/manual/en/mysqli-stmt.get-result.php