【问题标题】:How to get PDO up and running?如何启动并运行 PDO?
【发布时间】:2012-07-05 01:16:38
【问题描述】:

我是一个 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 工作?

感谢您的帮助!

【问题讨论】:

  • 你是否在php.ini中启用了PDO扩展?
  • 一些提示:PDO drivers sqlite, sqlite2new PDO('mysql'...Error!: could not find driver
  • 我会读到,因为您只有用于 PDO 的 sqlite 和 sqlite2 驱动程序,因此它抱怨的不是它不能做 PDO,而是它不能做 mysql

标签: php mysql pdo


【解决方案1】:

您还应该添加 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

【讨论】:

  • 不客气。我总是很乐意让人们远离古老的 mysql_ 函数 :)
猜你喜欢
  • 2018-12-10
  • 2021-09-27
  • 2020-03-13
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2014-02-06
相关资源
最近更新 更多