Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put the results of a MySQLi prepared statement into an associative array?

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?

like image 350
zeckdude Avatar asked Jun 14 '09 23:06

zeckdude


People also ask

What does fetch_ assoc() return?

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.

How does fetch_ assoc work?

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.

What is get_ result in php?

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.

Which function is used in MySQLi with prepared statements?

There's also a function to simply free the memory associated with the MySQLi result and prepared statement, respectively: $result->free() and $stmt->free() .


1 Answers

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();
like image 133
maikel Avatar answered Oct 28 '22 06:10

maikel