<?php
class cls_mysql
{
protected $link_id;
function __construct($dbhost,$dbuser,$dbpw,$dbname='',$charset='GB2312')
{
if(!($this->link_id=mysql_connect($dbhost,$dbuser,$dbpw)))
{
$this->ErrorMsg("Can't pConnect MySQL Server($dbhost)!");
}
mysql_query("SET NAMES ".$charset,$this->link_id);
if($dbname)
{
if(mysql_select_db($dbname,$this->link_id)===false)
{
$this->ErrorMsg("Can't slect MYSQL database($dbname)!");
return false;
}
else
{
return true;
}
}
}
public function select_database($dbname)
{
return mysql_select_db($dbname,$this->link_id);
}
public function fetch_array($query,$result_type=MYSQL_ASSOC)
{
return mysql_fetch_array($query,$result_type);
}
public function query($sql)
{
return mysql_query($sql,$this->link_id);
}
public function affected_rows()
{
return mysql_affected_rows($this->link_id);
}
public function num_rows($query)
{
return mysql_num_rows($query);
}
public function insert_id()
{
return_insert_id($this->link_id);
}
public function selectLimit($sql,$num,$start=0)
{
if($start==0)
{
$sql.=' LIMIT '.$num;
}
else
{
$sql.=' LIMIT '.$start.', '.$num;
}
return $this->query($sql);
}
public function getOne($sql,$limited=false)
{
if($limited=true)
{
$sql=trim($sql.' LIMIT 1');
}
$res=$this->query($sql);
if($res!=false)
{
$row=mysql_fetch_row($res);
return $row[0];
}
else
{
return false;
}
}
public function getAll($sql)
{
$res=$this->query($sql);
if($res!==false)
{
$arr=array();
while($row=mysql_fetch_assoc($res))
{
$arr[]=$row;
}
return $arr;
}
else
{
return false;
}
}
function ErrorMsg($message='',$sql='')
{
if($message)
{
echo "<b> error info</b>:$message\n\n";
}
else
{
echo "<b>MySQL server error report:";
print_r($this->error_message);
}
exit;
}
}
?>
5.2 建立test.php
复制代码 代码如下:
<?php
include("cls_mysql.php");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=GB2312" />
<title>Mysql类库测试</title>
</head>
<body>
<?php
$sql="Select * from member";
$db=new cls_mysql('localhost','root','123','club','GB2312');
$result=$db->selectLimit($sql,'3'); //从数据库中返回3个会员资料
if($result)
{
while($row=$db->fetch_array($result))
{
echo "会员编号: " .$row['no'].",姓名:".$row['name']."<br />";
}
}
?>
</body>
</html>
6 总结
6.1 mysql_connect():建立与MySQL服务器的连接
6.2 mysql_select_db():选择数据库
6.3 mysql_query():执行数据库查询
6.4 mysql_fetch_array():获取数据库记录
6.5 mysql_num_rows():获取查询得到的记录数
6.6 mysql_affected_rows():最近一次操作影响到的行数
6.7 mysql_insert_id():最近一次插入记录的ID值
您可能感兴趣的文章: