我有一个问题,当我要将我的PHP代码连接到我的数据库时,此错误在图片中显示了我 但是,当我通过终端连接数据库时,它就可以工作了
https://i.imgur.com/cpIzV9E.png
<?php
$host='localhost';
$db='canda';
$user='root';
$pass='123456789';
try{
new PDO("mysql:host=".$host
."; dbname=".$db,
$user, $pass);
}catch (PDOException $e) {
echo $e;
}
PDOException:SQLSTATE [HY000] [2002] /Users/mac/Desktop/test.php:11中没有这样的文件或目录:堆栈跟踪:#0 /Users/mac/Desktop/test.php(11):PDO -> __ construct('mysql:host = loca ...','root','password')#1 {main}
答案 0 :(得分:-1)
那里有更清洁的版本;
$host = DB_HOST; // just ignore constants //
$user = DB_USER;
$pass = DB_PASS;
$dbname = DB_NAME;
$dsn = 'mysql:host=' . $host . ';dbname=' . $dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
new PDO($dsn, $user, $pass, $options);
}
// Catch any errors
catch(PDOException $e){
echo $e;
}
如果这行不通,那么您去pdoexception-sqlstatehy000-2002-no-such-file-or-directory