crmepham
crmepham

Reputation: 4740

PHP - Unable to echo out values in returned array

I have a function that retrieves data from a Mysql database, stores the values in an array and returns that array to the calling function.

$stmt = $dbh->prepare("SELECT img_file_name FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_active = 0 AND post_id = ? ");
        $stmt->bindParam(1,$post_id);
        $stmt->execute();

        $resultarray = array();

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

                $resultarray[] = $row;
        }

        return $resultarray;

I am attempting to echo out the $values within that array like this:

$resultarray = get_post_data($post_id);

print_r($resultarray);

foreach($resultarray as $key => $value){
    echo 'The value is: '. $value . '<br />';
}

But when I browse the webpage it is only echoing out "Array". When I print_r the array the values are definitely in the array. So how do I correctly display those values?

Upvotes: 0

Views: 426

Answers (3)

Amarnasan
Amarnasan

Reputation: 15529

foreach($resultarray as $row){
    foreach($row as $key=>$value) {
        echo 'The value is: '. $value . '<br />';
    }
}

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174937

Makes sense. when you save $row to your array, you're actually creating a 2d array. $row is an array, even though you only selected one value. If you only want to save the image file name you selected, save $row['img_file_name'] to the array, instead if $row.

Alternatively, echo $value['img_file_name'] instead of $value.

Upvotes: 4

flowfree
flowfree

Reputation: 16462

Replace this line

$resultarray[] = $row;

with this:

$resultarray[] = $row['img_file_name'];

Upvotes: 1

Related Questions