Can't open SQL data base using PDO

I’m using Kevin Yank’s PHP & MySQL: Novice to Ninja and am trying to connect with a data base using the PHP Data Object (PDO) Extension. Here is the code I’m using.

try
{
$pdo = new PDO('mysql:host=localhost; dbname=ijdb', 'root', 'da_password');

}

catch (PDOException $e)

{
echo "Unable to open database -  error message from catch clause";
exit();
}

... and I get the following error message:   "Unable to open database - error message from catch clause"

However if I use another technique to connect to the data base it works. Here is that code:

$link = mysqli_connect('localhost', 'root', 'dbb11446');

if(!$link)
{
    $error = 'Unable to connect to the database server.';
    include 'error.html.php';
    exit();
}

if(!mysqli_set_charset($link, 'utf8'))
{
    $error = 'Unable to set the database connection encoding.';
    include 'error.html.php';
    exit();
}

if(!mysqli_select_db($link, 'ijdb'))
{
    $error = 'Unable to locate the ijdb database.';
    include 'error.html.php';
    exit();
}


echo "Database opened";

… and I get the “Database opened” message.

The host name, database name, user name and password are the same in both cases but the PDO version fails.

What might be the problem.

Dave

Change your error section to this to give a more meaningful error and see what it says:


catch (PDOException $e){
    echo "Unable to open database - Message: " . $e->getMessage();
   exit();
}

Also, it’s easier to read pasted code if you wrap it in [ CODE ], [ /CODE ], and [ PHP ], [ /PHP ] (respectively, without the spaces) tags.

I added the expanded error message and I get “Message: could not find driver” … I’m not sure what driver it’s looking for or where it should reside.

Dave

It means you don’t have the PDO extension installed/setup. You may have to check the options if you’re using MAMP/XAMP/WAMP etc, or if you have everything installed on a server you may need to re-compile PHP to include the PDO extension.

Whatever you do, do not use the standard mysql library in any production environment. PHP is getting rid of it since it’s not really maintained, it has security flaws for days, it lacking important features, etc. You can try MySQLi instead of PDO if you want, but one or both need to be compiled with PHP before you can use them in your scripts.

If you tell us a little more about your PHP setup we may be able to help you some in getting it up and running.

Have a look in your php.ini file for a line that looks like:

extension=php_pdo_mysql.dll

If there is a ; at the start of that line, remove that ; then save and reboot the server.

When posting code in the forums, please remember to remove any passwords!