class MysqlConn
{
public $dbtype;
public $host;
public $dbname;
public $user;
public $pwd;
function __construct($dbtype,$dbname,$host,$user,$pwd)
{
$this->dbtype=$dbtype;
$this->host=$host;
$this->dbname=$dbname;
$this->user=$user;
$this->pwd=$pwd;
if($this->dbtype=="mysql" || $this->dbtype=="mssql")
{
$dsn="$this->dbtype:host=$this->host;dbname=$this->dbname";
}
else
{
$dsn="$this->dbtype:dbname=$this->dbname";
}
try
{
$conn = new PDO($dsn, $this->user, $this->pwd); //初始化一个PDO对象,就是创建了数据库连接对象$pdo
$conn->query("set names utf8");
return $conn;
}
catch(PDOException $e)
{
die("Error!: " . $e->getMessage() . "<br/>");
}
}
}
$conn=new MysqlConn("mysql","dzxx_db","localhost","admin","123");//数据库连接类实例化,执行连接操作,返回连接标识
3 回答
天使之翼死神之镰
TA贡献81条经验 获得超102个赞
$dsn的值有问题,正确的应该分别是 $dsn=$this->dbtype.":host=".$this->host.";dbname=".$this->dbname;和$dsn=$this->dbtype.":dbname=".$this->dbname;
错过了年华
TA贡献56条经验 获得超22个赞
class ConnDB{ var $dbtype; var $host; var $user; var $pwd; var $dbname; //构造方法 function ConnDB($dbtype,$host,$user,$pwd,$dbname){ $this->dbtype=$dbtype; $this->host=$host; $this->user=$user; $this->pwd=$pwd; $this->dbname=$dbname; } //实现数据库的连接并返回连接对象 function GetConnId(){ if($this->dbtype=="mysql" || $this->dbtype=="mssql"){ $dsn="$this->dbtype:host=$this->host;dbname=$this->dbname"; }else{ $dsn="$this->dbtype:dbname=$this->dbname"; } try { $conn = new PDO($dsn, $this->user, $this->pwd); //初始化一个PDO对象,就是创建了数据库连接对象$pdo $conn->query("set names utf8"); return $conn; } catch (PDOException $e) { die ("Error!: " . $e->getMessage() . "<br/>"); } } }
上面这个是原本的类,可没见需要像你那样写啊
添加回答
举报
0/150
提交
取消