0
votes

I'm kind of a newbie PHP programmer and never heard about PDO until a few days ago. Up until now I have just used the default MySQL functions in PHP for my website, but from what I've been reading it seems like I really should switch to PDO.

I recompiled Apache, enabling PDO, but when I try to connect with the following code:

try 
{
    $dbh = new PDO('mysql:host=localhost;dbname=' . $dbname, $user, $pass);
}
catch (PDOException $e) 
{
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

I get the error:

Error!: could not find driver

I ran phpinfo() and found the following relevant to PDO:

'./configure' '--disable-fileinfo' '--disable-phar' '--enable-bcmath' '--enable-calendar' '--enable-ftp' '--enable-gd-native-ttf' '--enable-libxml' '--enable-magic-quotes' '--enable-mbstring' '--enable-pdo=shared' '--enable-sockets' '--prefix=/usr/local' '--with-apxs2=/usr/local/apache/bin/apxs' '--with-curl=/opt/curlssl/' '--with-freetype-dir=/usr' '--with-gd' '--with-gettext' '--with-imap=/opt/php_with_imap_client/' '--with-imap-ssl=/usr' '--with-jpeg-dir=/usr' '--with-kerberos' '--with-libxml-dir=/opt/xml2/' '--with-mcrypt=/opt/libmcrypt/' '--with-mysql=/usr' '--with-mysql-sock=/var/lib/mysql/mysql.sock' '--with-mysqli=/usr/bin/mysql_config' '--with-openssl=/usr' '--with-openssl-dir=/usr' '--with-pcre-regex=/opt/pcre' '--with-pdo-sqlite=shared' '--with-png-dir=/usr' '--with-sqlite=shared' '--with-xpm-dir=/usr' '--with-zlib' '--with-zlib-dir=/usr'


PDO
PDO support enabled
PDO drivers     sqlite, sqlite2

pdo_sqlite
PDO Driver for SQLite 3.x   enabled
SQLite Library  3.7.7.1

How do I get PDO working?

Thanks for your help!

1
Have you enabled the PDO extension in php.ini?Tio
Some tips: PDO drivers sqlite, sqlite2, new PDO('mysql'... and Error!: could not find driverEsailija
I would read that as you only have the sqlite, and sqlite2 drivers for PDO, hence its complaining not that it cant do PDO, but it cant do mysqlBugFinder

1 Answers

3
votes

You should also add the pdo-mysql extension:

--with-pdo-mysql=shared

Some extra info:

Also always add the encoding of the database:

$dbh= new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

Always disable emulated prepared statements (for mysql)

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Since you are just starting with PDO I also suggest this tutorial: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers