1

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

2 Answers 2

1

You need to use:

while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {

}

Instead of the for loop. You are also highly encouraged to use { and } for things like loops :)

Sign up to request clarification or add additional context in comments.

Comments

1

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
}

2 Comments

actually I need multiple bits of data but wanted to make the example easier just by using img_id. How do I get each set of data into its own key in the array?
@crm using PDOStatement::fetchAll()? You can use PDO::FETCH_COLUMN as the fetch type for PDOStatement::fetchAll(), which gives you what [i think] you're looking for. Though if you plan on looping through the results manually I'd stay away from fetchAll and use fetch, as above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.