how to properly use while loop in PDO fetchAll

后端 未结 1 603
眼角桃花
眼角桃花 2020-11-29 06:07

please be easy on me, i just started learning PDO and still finding my way how to convert my mysqli to PDO.

so i have a function to get the contents from my database

相关标签:
1条回答
  • 2020-11-29 06:41

    With fetchAll() you don't have to use while at all. As this function returns an array, you have to use foreach() instead:

    function getContent() {
        $db = PDOconn();
        $query = "SELECT * FROM posts ORDER BY id DESC LIMIT 0,3";
        $sql = $db->prepare($query);
        $sql->execute();
        return $sql->fetchAll();
    }
    
    $data = getContent();
    foreach($data as $row) {
        $id = $row['id'];
        $content = $row['content'];
    }
    
    0 讨论(0)
提交回复
热议问题