2012-07-04 44 views
0

我是一个新手PHP程序员,直到几天前才听说过PDO。到目前为止,我只是在PHP中为我的网站使用了默认的MySQL函数,但从我一直在阅读的内容来看,似乎我应该切换到PDO。如何让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

您是否在php.ini中启用了PDO扩展? – Tio

+0

一些提示:'PDO驱动程序sqlite,sqlite2','新的PDO('mysql'...'和'错误!:找不到驱动程序' – Esailija

+0

我会阅读,因为你只有sqlite和PDO的sqlite2驱动程序,因此它的抱怨不是它不能做PDO,但它不能做mysql – BugFinder

回答

3

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

--with-pdo-mysql=shared 

一些额外的信息:

而且随时添加数据库的编码:

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

始终禁用模拟预处理语句(for mysql)

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

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

+0

伟大的链接,并感谢您的回答! – Nate

+0

不客气,我总是乐意将人们从古代的mysql_函数中移走:) – PeeHaa

相关问题