简体   繁体   English

PDO_mysql驱动程序不起作用

[英]PDO_mysql driver doesn't work

I'm using Apache server on Windows 8, XAMPP 1.8.1, PHP 5.4.7 and MySQL. 我在Windows 8,XAMPP 1.8.1,PHP 5.4.7和MySQL上使用Apache服务器。 I've decided to convert my code to PDO. 我决定将我的代码转换为PDO。

Checking my phpinfo() it appears that the PDO driver for MySQL is enabled, but I still keep on getting the "could not find driver" error. 检查我的phpinfo() ,似乎已启用MySQL的PDO驱动程序,但我仍然继续收到“找不到驱动程序”错误。

Here's the code: 这是代码:

<?php 
//connect to database

$config['db'] = array(
    'host'           => 'localhost',
    'username'       => 'root',
    'password'       => '',
    'dbname'         => 'x'
    );

$db = new PDO("
    pdo_mysql:host=     " .$config['db']['host']. ";
    dbname=             " .$config['db']['dbname']. ";
    username=           " .$config['db']['username'].";
    password=           " .$config['db']['password']."
    ");
?>

And the error: 错误:

Fatal error: Uncaught exception 'PDOException' with message 'could not find driver' 致命错误:消息为“找不到驱动程序”的未捕获异常“ PDOException”

Any suggestions? 有什么建议么?

让我建议您参考手册页并从中获取正确的 DSN字符串示例

如果将DSN前缀从pdo_mysqlmysql怎样?

As manual says link 正如手册所说的链接

You should format your dsn in this way: DRIVER:host=YOURHOST;dbname=YOURDB 您应该通过以下方式格式化dsn: DRIVER:host=YOURHOST;dbname=YOURDB

Also to create the instance you should act like this: $db = new PDO($dsn, $username, $password) 同样,要创建实例,您应该像这样: $db = new PDO($dsn, $username, $password)

Also I forgot to say (as other users have pointed out) your DRIVER is "mysql" and not pdo_mysql 我也忘了说(正如其他用户指出的那样),您的驱动程序是“ mysql”而不是pdo_mysql

In the end there were 2 problems with the code: 最后,代码有两个问题:

1. pdo_mysql -> mysql 1. pdo_mysql-> mysql

2. username and password should be passed as variables and not as strings . 2.用户名和密码应作为变量而不是字符串传递。

The correct code is: 正确的代码是:

$config['db'] = array(
    'host'           => 'localhost',
    'username'       => 'root',
    'password'       => '',
    'dbname'         => 'x'
    );

$db = new PDO (
    "mysql:host=".$config['db']['host'].";dbname=".$config['db']['dbname']."",
    $config['db']['username'], 
    $config['db']['password'] 
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM