简体   繁体   English

foreach在使用pdo的php中不起作用

[英]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. 我在PHP项目中使用了PDO,但我不知道为什么这不起作用。 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. 我使用一个foreach循环来显示数据。 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: 在函数Read_post中,您具有以下这一行:

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

It will not return an array, it will return a PDO object. 它不会返回数组,它将返回一个PDO对象。 You can't iterate over a PDO object in the same way as an array. 您不能以与数组相同的方式遍历PDO对象。 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 foreachvar_dump($post)回显数组的$value以检查数组是否包含

something 某物

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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