bobafart
bobafart

Reputation: 397

PDO - query not returning results - output is empty and not sure why

Trying to perform my first simple PDO query. Nothing is being output.

The fields in the mySQL table are indeed full of content, they are not blank. Connecting to the db is working.

My output is as follows:

Connected to database.
dfsdfs 1object(PDO)#2 (0) { }

These code lines are not outputting:

        PDO::errorInfo()
    echo "Performing a select: <br>";
    print_r($row);  

These code lines are also not outputting:

    <h2><?php echo $row['articleTitle']; ?></h2>
    <?php echo $row['articleBody']; ?>

My code:

<?php

/*** mysql hostname ***/
$hostname = 'removed';
/*** mysql username ***/
$username = 'removed';
/*** mysql password ***/
$password = 'removed';
function testdb_connect ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password);
return $dbh;
}

try {
$dbh = testdb_connect ($hostname, $username, $password);
echo 'Connected to database';
} catch(PDOException $e) {
echo $e->getMessage();
}
$dbh = testdb_connect ($hostname, $username, $password);

$id=$_GET[id];
echo 'dfsdfs '.$id;
var_dump($dbh);
$sql="SELECT * FROM 'radiologyArticles' WHERE 'id' = :id";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
    if (!$stmt) {
      echo "\nPDO::errorInfo():\n";
      print_r($dbh->errorInfo());
    }
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {  
echo "Performing a select: <br>";
print_r($row);                                  
?>
<section>
    <header>
        <h2><?php echo $row['articleTitle']; ?></h2>
    </header>
    <p>
    <?php echo $row['articleBody']; ?>
    </p>
</section>
<?php
}
// close the PDO connection
$link = null;
?>

Upvotes: 0

Views: 278

Answers (1)

jeroen
jeroen

Reputation: 91734

I'm not sure why you don't see any errors, but this line is wrong:

$sql="SELECT * FROM 'radiologyArticles' WHERE 'id' = :id";

You should not use quotes (single or double) for table- or column names. If you need to quote them (in case of reserved words for example), you need backticks:

$sql="SELECT * FROM `radiologyArticles` WHERE `id` = :id";

To make sure that PHP throws an exception when it encounters a problem, you could change your connetion string to:

$dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

Upvotes: 1

Related Questions