这是我的程序描述。我尝试创建一个具有不同方法的数据库连接类,这些方法的不同之处在于它们从数据库中提取记录的方式。
我想做的是——将类属性设置为 PDO 连接参数,并使用这些属性创建默认构造函数。每当我需要数据时,我都会调用那些应该返回记录的方法。
问题是:我认为用于创建 PDO 对象的连接字符串是正确的,但它会显示错误:未捕获异常“PDOException”,消息为“SQLSTATE[HY000] [2002] 无法连接到本地” MySQL 服务器通过套接字 '/var/lib/mysql/mysql.sock' (2)
你能帮我弄清楚到底发生了什么吗? 您能否与我分享创建安全、健壮和动态可访问的数据库类或方法的技术和想法?我将不胜感激。提前致谢!
代码:
<?php
class DatabaseConnection {
private $hostname;
private $dbname;
private $username;
private $password;
public function __construct() {
$this->hostname = "hostname";
$this->dbname = "database";
$this->username ="username";
$this->password = "password";
}
function getDataFromTable($query){
echo $dns;
$db = new PDO("mysql:host = {$this->hostname} ; dbname = {$this->dbname}", $this->username, $this->password);
// stuffs ...
}
}
?>
最佳答案
清除空格:
$db = new PDO(
"mysql:host={$this->hostname};dbname={$this->dbname};charset=utf8",
$this->username,
$this->password
);
使用 PHP >= 5.3.6,您可以将字符集添加到 dsn。 (charset=utf8
)
另一个可能的问题:( http://php.net/manual/de/ref.pdo-mysql.connection.php )
When the host name is set to "localhost", then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against libmysqlclient then the location of the socket file is at libmysqlclient's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.
因此,请尝试使用 127.0.0.1
而不是 localhost
作为主机名,或者查看 here .
关于php - 从 PHP 类和 DBMS 技术创建 PDO 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20230076/