我使用PHP的define()为我的PDO连接字符串(即)定义常量。在mysqli中。但是,它似乎没有用。使用以下代码时,我不断收到错误:Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
:
当我不使用PHP的define()函数来传递连接变量时,PDO连接字符串将起作用。我正在使用PHP 7,MySQL 8和Apache 2.4。
下面的问题代码:
error_reporting(E_ALL); //check all type of errors
ini_set('display_errors', 1); // display those if any happen
//Database Connection Constant
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_NAME', 'gallery_db');
echo DB_PASS;
//phpinfo();
//$conn = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
try {
$dbc = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . "," . DB_USER, DB_PASS);
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($dbc) {
echo "connected";
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
工作连接代码:
$servername = 'localhost';
$username = 'root';
$password = 'root';
$dbn = 'gallery_db';
//phpinfo();
try {
$dbc = new PDO("mysql:host=$servername;dbname=$dbn", $username, $password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false
));
// set the PDO error mode to exception
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($dbc) {
echo "connected";
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
为什么PHP define()在PDO的连接字符串中不起作用?
答案 0 :(得分:-1)
首先尝试这种方法:
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.",". DB_USER, DB_PASS);
这只有两个参数,但是PDO需要3:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
https://php.net/manual/en/pdo.connections.php
发生的事情是您的密码常数有效,但进入了连接的用户名部分。
修复:
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
答案 1 :(得分:-1)
更改
$ dbc =新的PDO(“ mysql:host =”。DB_HOST。“; dbname =”。DB_NAME。“,”。DB_USER,DB_PASS);
到
$ dbc =新的PDO(“ mysql:host =”。DB_HOST。“; dbname =”。DB_NAME,DB_USER,DB_PASS);