Reputation: 1359
I have a mysql query that fetches a number of rows from the database and I want to bind those results into a multidimensional array.
$sample = array();
$samples = array();
//bind results into $sample array
$stmt->bind_result($sample['id'], $sample['name'], $sample['image_path'],
$sample['main_text'], $sample['nose'], $sample['palate'], $sample['finish'],
$sample['sample_price'], $sample['retail_price'], $sample['retail_url']);
//fetch each row of results and push the resultant array into the $samples array
while($stmt->fetch()) {
$samples[] = $sample;
}
Here's a pseudo-code instantiation of what I'm hoping the above would achieve:
$samples = array(
0 => array(
"id" => the item's id
"name" => the item's name
"image_path" => the item's image pgae
"main_text" => the second item's main text
"nose" => etc
"finish" => etc
"palate" => etc
"sample_price" => etc
"retail_url" => etc
1 => array(
"id" => the second item's id
"name" => the second item's name
"image_path" => the second item's image page
"main_text" => the second item's main text
"nose" => etc
"finish" => etc
"palate" => etc
"sample_price" => etc
"retail_url" => etc
Instead, I'm ending up with an multidimensional array full of identical items. More specifically, if I step through the code:
My assumption would be that $sample
is somehow being pushed onto the array by reference, but that doesn't make sense to me as php assigns arrays by value.
Anyone have any idea what I might be doing wrong?
Update: I am aware of the get_result() function. Unfortunately, that only works if the mysqli extension was compiled using the MySQL native driver - this is something that is pretty difficult to guarantee.
Upvotes: 0
Views: 812
Reputation: 17289
As simple as:
$stmt->store_result();
$result = $stmt->get_result();
$samples = $result->fetchAll(MYSQLI_ASSOC);
UPDATE
$stmt->bind_result($r_id, $r_name, $r_image_path,
$r_main_text, $r_nose, $r_palate, $r_finish,
$r_sample_price, $r_retail_price, $r_retail_url);
while($stmt->fetch()) {
$samples[] = array('is'=>$r_id,
'name'=>$r_name,
'image_path'=>$r_image_path,
'main_text'=>$r_main_text,
'rose'=>$r_nose,
'palate'=>$r_palate,
'finish'=>$r_finish,
'sample_price'=>$r_sample_price,
'retail_price'=>$r_retail_price,
'retail_url'=>$r_retail_url);
}
Upvotes: 2