简体   繁体   中英

foreach is not working in php with pdo

I am using PDO with my PHP project and I don't know why this is not working. It is not showing any error.

I have a function to read data from a database:

function Read_post($con,$table,$limit=6){

    try {
        $query = "SELECT * FROM {$table} ORDER BY  id DESC LIMIT {$limit}";
        $stmt = $con->prepare( $query );
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return "ERROR". $e->getMessage();
    }

}

and I use a foreach loop to display the data. But it is not showing anything:

<?php $posts = Read_post($con,"posts"); ?>

<?php foreach ($posts as $key) {
    echo "something ";
    echo $key["title"];
} ?>

It is not showing the other text as well like if i echo something else only text.

Inside your function Read_post, you have this line:

return $stmt->fetch(PDO::FETCH_ASSOC);

It will not return an array, it will return a PDO object. You can't iterate over a PDO object in the same way as an array. Try this:

$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;

echo the $value of the array in foreach or var_dump($post) to check the array contains

something

<?php foreach ($posts as $value) {
        echo "something ";
        echo $value;
    } ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM