PDO - 在非对象上调用成员函数 fetch()

2022-01-20 00:00:00 database fetch php pdo fatal-error

我的错误:

( ! ) 致命错误:在第 13 行的 C:wampwwwPDOindex.php 中的非对象上调用成员函数 fetch()

我的代码:

<?php 

$config['db'] = array(
    'host'      =>      'localhost',
    'username'  =>      'root',
    'password'  =>      '',
    'dbname'    =>      'learnpdo'
);

$db = new PDO('mysql:host='.$config['db']['host'].';dbname'.$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$query = $db->query("SELECT articles . title FROM articles");

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    echo $row['title'];
}

我知道有很多这样的问题,但似乎没有一个答案有效.

I know there are many questions like this, but none of the answers seem to work.

谢谢

以上已修复,感谢以下所有人.:) 现在我又遇到了一个错误:

Above is fixed, thanks to everyone below. :) Now I'm getting another error:

注意:未定义的索引:第 7 行 C:wampwwwPDOindex.php 中的 id

这是我的数据库:

http://d.pr/i/vcod

这是我的代码:

$db = new PDO('mysql:host=localhost;dbname=learnpdo;charset=UTF-8', 'root', '');
$query = $db->query("SELECT `articles`.`title` FROM `articles`");

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    echo $row['id'];
}

推荐答案

代替:

$query = $db->query("SELECT articles . title FROM articles");

试试:

$query = $db->query("SELECT title FROM articles");

编辑

试试:

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    echo $row['title'];
}

相关文章