简体   繁体   中英

Query not returning anything. How can I input test to make sure that I know it's working?

After being advised that the old method of access a database were not correct. I have now started using the PDO object. I am setting up a simple query but I am not getting any results back. Any help or advise would be appreciated. It is not even printing the query back to me. Would turning on error messages help?

<?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>';
//}

I would recommend you read up on PDO and error handling and reporting.

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

They should show you how to easily get proper errors from your sql query so you can see whats going wrong.

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 `

PHP manual :

<?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";
    }
}
?>

You don't need quotes on table or column names.

Why dont you prepare your statements first and then execute them?

$stmt = $db->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();

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