如何启动并运行 PDO


How to get PDO up and running?

我是一个新手PHP程序员,直到几天前才听说过PDO。到目前为止,我刚刚为我的网站使用了PHP中的默认MySQL函数,但是从我所阅读的内容来看,我似乎真的应该切换到PDO。

我重新编译了 Apache,启用了 PDO,但是当我尝试使用以下代码连接时:

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

我收到错误:

Error!: could not find driver

我运行了phpinfo(),发现以下内容与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

如何让 PDO 工作?

感谢您的帮助!

您还应该添加 pdo-mysql 扩展:

--with-pdo-mysql=shared

一些额外信息:

还要始终添加数据库的编码:

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

始终禁用模拟预准备语句(对于 mysql)

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

由于您刚刚开始使用PDO,因此我也建议您使用本教程:http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers