Querying a table using PDO


Looking for a bit of help if possible. I’m using PDO for the first time to connect to a database and then query it. Now the PDO connection I have created is like so:

try {
  $dbh = 'mysql:host=ddddddddddd;dbname=sssssssssssss';
  $dbc = new PDO($dbh, 'iiiiiiiiiiiiiii','xxxxxxxxxxxxxx');
  $dbc ->setAttribute(PDO::ATTR_EMULATE_PREPARES, True);
  echo "sucessfully connected";
} catch (PDOException $e) {
  echo 'Failed: ' .$e->getMessage();


Now I know this connection is working as I echo “sucessfully connected” in the try/catch block to my page.

However on a page where I include my connection and query a database like so:

//Include PDO connection

$result = mysql_query("SELECT * from db");
   $num = mysql_num_rows($result);
   $n = 0;	
    while($row = mysql_fetch_array($result)){
       echo ''.$row['name'].''';  

It then shows a load of ‘access denied’ messages, A link to the server could not be established etc when I run that query?

Any ideas?

You’re using mysql_* functions to query the database, you need to use the methods provided to you by the PDO object. In your case, $dbc.

See, PDO::Query and [URL=“http://www.php.net/manual/en/pdo.prepare.php”]PDO::Prepare. :slight_smile:

first impulse: Unless you’ve named your database table ‘db’, your query’s not quite right. Perhaps posting a schema of that table would be a good idea too.
Second impulse: too many quotation marks on the echo line.

Magic - worked it out thanks!!

Hey, no worries. :slight_smile:

Try [fphp]var_dump[/fphp]'ing $row to see what it contains.

Thanks. Sorry for the dumb questions! Doh!!

One last thing i’m probably being thick about. I’m getting no error messages now, but the ‘.$ROW[‘name’].’ is not outputting on the page?

I would guess it’s because you’re using $dbh and not $dbc. :slight_smile:

Thanks, had a look at that before, but don’t quite figure how to get it working with a while loop:

//Include PDO connection

$SQL = "SELECT * from db";

foreach ($dbh->query($SQL) as $ROW){
       echo ''.$ROW['name'].''';  

But get the message Call to a member function query() on a non-object