我是一名新手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正常工作?
感谢您的帮助!
答案 0 :(得分:3)
您还应该添加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