您的位置:首页 > 编程语言 > PHP开发

PHP MySql的dql和dml操作的封装,成为固定的工具类

2015-07-14 20:18 1001 查看
mysql_class.php:

<span style="font-size:18px;"><?php
class SqlTool{
private $conn;
private $host="localhost";
private $user="root";
private $password="111111";
private $db="test";
function SqlTool(){
$this->conn=mysql_connect($this->host,$this->user,$this->password);
if(!$this->conn){
die("对不起,连接数据库失败<br/>错误原因:".mysql_error());
}
mysql_select_db($this->db,$this->conn);//选择数据库
mysql_query("set names utf8");
}
//实现对 dql语句:select 的封装
public function execute_dql($sql){
//执行数据库dql语句,即查询操作
$res=mysql_query($sql,$this->conn) or die("查询失败,失败原因".mysql_error());
return $res;
}
//实现对 dml语句:update,delete ,insert 的封装
public function execute_dml($sql){
$b=mysql_query($sql,$this->conn);
if(!$b){
//return 0; //运行失败
echo "对不起,操作失败";
}else{
//受影响,返回行数;不受影响,返回-1
if(mysql_affected_rows($this->conn)>0){
//return 1; //运行成功
echo "操作成功!";
}else{
//return 2; //成功,但没有影响行数
echo "操作成功,但是行数没有受到影响";
}
}
//关闭连接
mysql_close($this->conn);
}
}
?>
</span>

调用上面文件生成的类,实现数据库的增删改查操作:

<span style="font-size:18px;"><?php
require_once "mysql_class.php";//引入SqlTool的类文件

/************************dml操作******************************/
/*//添加数据
$sql="insert into test (name,id,class,age) values('xuning_a',md5('78989'),'xiaohei@qq.com',18)";//Sql语句
$SqlTool=new SqlTool();
$res=$SqlTool->execute_dml($sql);
*/
//删除数据
/*
$sql="delete from test1 where id = 21";//Sql语句
$SqlTool=new SqlTool();
$res=$SqlTool->execute_dml($sql);
*/
//修改数据
//$sql="update test set age=1000 where id=2";//Sql语句
//$SqlTool=new SqlTool();
//$res=$SqlTool->execute_dml($sql);
//dml操作,不需要再释放资源,只要最后关闭链接即可
/**********************dql操作*********************************/
//查询操作
$sql="select * from test";
$SqlTool=new SqlTool();
$res=$SqlTool->execute_dql($sql);
while($row=mysql_fetch_row($res)){  //显示所有的用户数据
foreach($row as $key =>$val){
echo "$key=>"."$val"."    ";
}
echo "<br/>";
}
//dql操作要释放资源,并关闭链接
mysql_free_result($res);
?>
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: