crmepham
crmepham

Reputation: 4740

PDO, MySQL Insert fetched data into an array

This question is related to this previous question: PDO, MySQL - How do I return an array from a function?

But I felt it wasn't specific enough.

I want to return each row of variables in its own key in an array so I can use them in the calling program.

This is the code I have so far but am not sure if its correct or even going in the right direction:

$total = $dbh->prepare("SELECT COUNT(post_id) FROM mjbox_posts");
        $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();

            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            for($i=0;$i<=$total;$i++){

                $resultarray[] = array("id"=>$row['img_id'],"filename"=>$row['img_file_name']);

            }

        }

        return $resultarray;

It appears the data does get inserted into the array and passed back to the calling program but it seems to duplicate each piece of data twice in the array:

Array ( [0] => Array ( [0] => Array ( [id] => 5 [filename] => fullsize/8520430289728860armor.jpg ) [1] => Array ( [id] => 5 [filename] => fullsize/8520430289728860armor.jpg ) [2] => Array ( [id] => 6 [filename] => fullsize/5535575154865203bg1.jpg ) [3] => Array ( [id] => 6 [filename] => fullsize/5535575154865203bg1.jpg ) [4] => Array ( [id] => 7 [filename] => fullsize/7598226850012898images.jpg ) [5] => Array ( [id] => 7 [filename] => fullsize/7598226850012898images.jpg ) ) )

Upvotes: 0

Views: 776

Answers (1)

Marc B
Marc B

Reputation: 360662

That code is broken. $total is going to be a mysql prepared statement handle, but you're using it in an integer comparison in your inner for(...) loop.

Your other query is wasting a lot of resources by fetching ALL the fields in your table, when you only need the two fields you're saving into your array.

Simplify that mess into:

query:

SELECT img_id AS id, img_file_name AS filename etc....

php:

$resultarray = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
   $resultarray[] = $row;
}

Upvotes: 2

Related Questions