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.
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.