<?php
class DB_Handler{
private $host;
private $db_name;
private $db_username;
private $db_password;
public $dbh;
public function __construct( $db_host, $db_name, $db_username, $db_password ){
$this->host = $db_host;
$this->db_name = $db_name;
$this->db_username = $db_username;
$this->db_password = $db_password;
}
public function connect(){
try{
$this->dbh = new PDO("mysql:host=$this->host; db_name =$this->db_name, $this->db_username, $this->db_password");
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
$error = "Error: ".$e->getMessage().'<br />';
echo $error;
return false;
}
return true;
}
}
$db_host = "localhost";
$db_name = "db_handler_01";
$db_username = "root";
$db_password = "sd";
$snowboard_db = new DB_Handler($db_host, $db_name, $db_username, $db_password);
$result = $snowboard_db->connect();
if($result){
echo "DB Connected <br>";
echo $snowboard_db;
}
else{
echo "DB is not Connected <br />";
}
?>
如果我给出了数据库的正确与否,它只显示数据库连接。请让我知道我在哪里做错了。
答案 0 :(得分:0)
这里有两个可能的问题。
第一个已经提到,你需要发送用户名和密码作为PDO构造函数的第二个和第三个参数。您正在发送第一个参数中的所有内容,原因是 - 可能放错地方 - 引用。
第二个问题是你告诉PDO在之后(或试图建立)连接时抛出异常。对于可能迟到的连接错误。
如果您还想捕获连接错误,可以使用所需选项向PDO构造函数发送第4个参数:
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->dbh = new PDO("mysql:host={$this->host}; db_name ={$this->db_name}",
$this->db_username, $this->db_password, $opt);
答案 1 :(得分:0)
$this->dbh = new PDO("mysql:host=$this->host; db_name =$this->db_name,
$this->db_username, $this->db_password");
语法不正确(你搞乱了最后的“)
正确的语法是:
$this->dbh = new PDO("mysql:host=$this->host;db_name=$this->db_name",
$this->db_username, $this->db_password);
顺便说一句,你不能回应你的课,它会回来:
捕获致命错误:类DB_Handler的对象无法转换为第49行的C:... \ index.php中的字符串