您的位置 >>> 星想互联 >>> 编程技术 >>> PHP基础
PHP数据库操作类的定义及使用
点击数:7771  发布时间2017-08-01 22:33:39
class myconn{
private $host;
private $user;
private $pwd;
private $db;
private $ch;

public function  __construct($host,$user,$pwd,$db,$ch){
$this->host=$host;
$this->user=$user;
$this->pwd=$pwd;
$this->db=$db;
$this->ch=$ch;
}

public function dbcon(){
//连接数据库
$links=mysql_connect($this->host,$this->user,$this->pwd);
mysql_query("set names ".$this->ch);
mysql_select_db($this->db,$links);
if(!$links){
echo "连接失败";
}else{
echo "连接成功";
}
}

function myquery($sql){
//不返回数据集,执行一条SQL语句
if($res=mysql_query($sql)){
return $res;
}else{
echo "操作失败";
};
}

function getone($sql){
//执行返回一条记录
$res=mysql_query($sql);
$rows=mysql_fetch_array($res);
return $rows;
}

function getarr($sql){
//执行返回多条数句
$res=mysql_query($sql);
$list=array();
while($rows=mysql_fetch_array($res)){
$list[]=$rows;
}
return $list;
}

function getnum($sql){
//返回操作数据记录数
$res=mysql_query($sql);
$num=mysql_affected_rows();
return $num;

}
}
//实例化类,依次执行删除、返回记录集等操作
$mylink=new myconn("121.32.236.12","db1051903","","db1051903","gbk");
$mylink->dbcon();
$mylink->myquery(sql);

$rs=$mylink->getone($sql);
echo $rs["title"]."
";
echo $rs["fdate"];

$ks=$mylink->getnum($sql);
echo "

".$ks;

$rs=$mylink->getarr($sql);
foreach($rs as $vs){
echo $vs["title"]."
";
}
?>

来源:咸宁网站建设