SqlTool.class.php
class SqlTool{
private $conn;
private $host = "localhost";
private $user = "root";
private $password = "root";
private $db = "test1";
/*
连接数据库的构造方法
*/
function SqlTool(){
$this->conn = mysql_connect($this->host , $this->user , $this->password);
if(!$this->conn){
die('连接失败'.mysql_error());
}
mysql_select_db($this->db,$this->conn);
mysql_query('set names gbk');
}
//select
function execute_dql($sql){
$res = mysql_query($sql,$this->conn);
return $res;
}
//insert、update、delete
function execute_dml($sql){
$obj = mysql_query($sql,$this->conn);
if(!$obj){
//return 0;//操作失败
die('操作失败'.mysql_error());
}else{
if(mysql_affected_rows($this->conn)>0){
//return 1;//操作成功
echo "操作成功";
}else{
//return 2;//行数没有收到影响
die('行数没有受影响');
}
}
}
}
?>
SqlToolTest.php
//引入数据库类文件
require_once "SqlTool.class.php";
//----------------dml操作------------------
//插入
//$sql = "insert into user1(name , password , email , age) values('李四',md5('123'),'lisi@',18)";
//删除
//$sql = "delete from user1 where id = 9";
//更新
//$sql = "update user1 set id=4 where name='李四'";
//创建一个SqlTool对象
//$SqlTool = new SqlTool();
//$res = $SqlTool->execute_dml($sql);
//--------------------dql操作--------------------
$sql = "select * from user1";
//创建一个SqlTool对象
$SqlTool = new SqlTool();
$res = $SqlTool->execute_dql($sql);
while($row=mysql_fetch_row($res)){
foreach($row as $key=>$val){
echo "--$val";
}
echo "
";
}
mysql_free_result($res);
/*if($res==0){
die('操作失败'.mysql_error());
}else if($res==1){
echo "操作成功";
}else if($res==2){
echo "行数没有受影响";
}*/
?>
创建数据库
create database test1;
创建数据表
create table user1(
id int auto_increment primary key,
name varchar(32) not null,
password varchar(64) not null,
email varchar(128) not null,
age tinyint unsigned not null
);
表结构
后续操作的图片结果: