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?
Definition and Usage. The fetch_assoc() / mysqli_fetch_assoc() function fetches a result row as an associative array. Note: Fieldnames returned from this function are case-sensitive.
Every time you fetch_assoc() it returns the current row and automatically advances to to the next row. So, the while loop does not tell the database to return the next row, the fetch_assoc() does that, the while loop ends when it gets an empty row.
Retrieves a result set from a prepared statement as a mysqli_result object. The data will be fetched from the MySQL server to PHP. This method should be called only for queries which produce a result set. Note: Available only with mysqlnd.
There's also a function to simply free the memory associated with the MySQLi result and prepared statement, respectively: $result->free() and $stmt->free() .
Update: Since PHP 5.3.0 you can get a mysqli_result object that provides a fetch_array method.
$sql = 'SELECT photographers.photographer_id, photographers.photographer_name
FROM photographers';
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_array();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With