I am using a function to retrieve multiple rows from a mysql database. I use a foreach to loop through each match. I want to be able add the id of each row to an array and return the array back to the calling program to then use the id's.
This is as far as I have tried to get, am I going in the correct direction?
$resultarray = array();
$resultarray[] = get_post_data($post_id);
print_r($resultarray);
code in function:
$stmt = $dbh->prepare("SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = ?");
$stmt->bindParam(1,$post_id);
$stmt->execute();
$resultarray = array();
foreach($stmt as $row):
$resultarray[] = $img_id = $row['img_id'];
endforeach;
return $resultarray;
Thanks
解决方案
If you just need the img_id field, why are you running select *?
$stmt = $dbh->prepare("SELECT img_id FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = ?");
$stmt->bindParam(1,$post_id);
$stmt->execute();
return $stmt->fetchAll();
Alternatively you could loop through the results manually (to validate/change the return array syntax) with:
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//code
}