利用封装方法封装数据库登录

在数据库使用的时候,每建一个php文件都要访问下数据库登录,如果必要时修改数据库登录信息,所有的php文件都要修改,为此,利用封装方法进行封装,以后只要修改这个文件就可以修改全部的php文件登录信息,
我这里建立了一个DBDA.class.php文件。

<?php

class DBDA
{
public $host = "localhost";
public $uid = "root";
public $pwd = "123";
public $dbname = "xiangmu";

public function Query($sql,$type=1)
{
$db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);
$result = $db->query($sql);

if($type=="1")
{
return $result->fetch_all();
}else
{
return $result;
}
}

//返回字符串的方法
public function StrQuery($sql,$type=1)
{
$db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);
$r = $db->query($sql);

if($type==1)
{
$attr = $r->fetch_all();
$str = "";
foreach($attr as $v)
{
$str .= implode("^",$v)."|";
}

return substr($str,0,strlen($str)-1);

}
else
{
return $r;
}
}

//返回JSON
function JSONQuery($sql,$type=1)
{
$db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);
$r = $db->query($sql);

if($type==1)
{
return json_encode($r->fetch_all(MYSQLI_ASSOC));
}
else
{
return $r;
}
}
}

 

posted @ 2017-02-26 10:52  终极用户  阅读(368)  评论(0编辑  收藏  举报