0

在被告知访问数据库的旧方法不正确之后。我现在已经开始使用 PDO 对象了。我正在设置一个简单的查询,但我没有得到任何结果。任何帮助或建议将不胜感激。它甚至没有将查询打印回给我。打开错误消息会有所帮助吗?

<?php

//print_r(PDO::getAvailableDrivers()); 

$config['db'] = array( //This is the config array with the database details
'host'              => 'localhost',
'username'          => 'root',
'password'          => '',
'dbname'            => 'website'
); 

$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname' . $config['db']['dbname'],         $config['db']['username'], $config['db']['password']); //Instanciate an PDO Object
$query = $db->query("SELECT 'articles'.'title' FROM 'articles'");//running a query from the database

print_r($query); //printing a query


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

3 回答 3

0

我建议您阅读 PDO 以及错误处理和报告。

http://php.net/manual/en/pdo.error-handling.phphttp://php.net/manual/en/pdo.errorinfo.php

他们应该向您展示如何轻松地从您的 sql 查询中获取正确的错误,以便您可以看到出了什么问题。

In you're case your query is wrong it should be $query = $db->query("SELECT title FROM articles"); No need to specify the tabl to pull from in your select param section and no need for single quotes. You should be using the back tick quote not single quote anyway `

于 2013-02-04T13:55:33.457 回答
-1

PHP手册:

<?php
function getFruit($conn) {
    $sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
    foreach ($conn->query($sql) as $row) {
        print $row['name'] . "\t";
        print $row['color'] . "\t";
        print $row['calories'] . "\n";
    }
}
?>

您不需要在表名或列名上加上引号。

于 2013-02-04T13:21:50.603 回答
-1

为什么不先准备语句然后执行它们?

$stmt = $db->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
于 2013-02-04T13:24:58.143 回答