<?php
header("content-type:text/html;charset=utf8");
class DB{
public $host;
public $username;
public $pwd;
public $db_name;
public $charset;
//构造方法
function __construct($host,$username,$pwd,$db_name,$charset){
$this->host=$host;
$this->username=$username;
$this->pwd=$pwd;
$this->db_name=$db_name;
$this->charset=$charset;
mysql_connect($this->host,$this->username,$this->pwd);
mysql_select_db($this->db_name);
mysql_query($this->charset);
}
//添加
function add($table,$first,$second){
$sql="insert into ".$table."(".$first.") values(".$second.")";
$res=mysql_query($sql);
return $res;
}
//查询所有数据
function select($table){
$sql="select * from $table";
$res=mysql_query($sql);
$list = array();
while($arr=mysql_fetch_assoc($res)){
$list[]=$arr;
}
return $list;
}
//查询单条数据
function find($table,$where){
$sql="select * from $table where $where";
$res=mysql_query($sql);
$arr=mysql_fetch_assoc($res);
return $arr;
}
//两表联查
public function TwoTable($table1,$table2,$id1,$id2,$id3,$limit){
$sql="select * from $table1 inner join $table2 on $table1.$id1=$table2.$id2 order by $id3 $limit";
$res= mysql_query($sql);
$ar=array();
while($arr=mysql_fetch_assoc($res)){
$ar[]=$arr;
}
return $ar;
}
//模糊查询
public function Limit($table,$offset,$length){
$sql="select * from $table limit $offset,$length";
//echo $res;
$res= mysql_query($sql);
$arr=array();
while($aar=mysql_fetch_assoc($re)){
$arr[]=$aar;
}
return $arr;
}
//删除
function del($table,$where){
$sql="delete from $table where $where";
$res=mysql_query($sql);
return $res;
}
// 修改
function save($table,$first,$where){
$sql="update $table set $first where $where";
$res=mysql_query($sql);
return $res;
}
}
?>
增加
<?php
require("db.class.php");
$db = new DB('127.0.0.1','root','root','php3yue','set names utf8');
$first="title,content";
$second ="'刘伟超','更多是一个'";
$res=$db->add('news',$first,$second);
if($res){
echo "添加成功";
}else{
echo "添加失败";
}
?>
删除
<?php
require("db.class.php");
$db = new DB('127.0.0.1','root','root','php3yue','set names utf8');
$res=$db->del('news','id=2');
if($res){
echo "删除成功";
}else{
echo "删除失败";
}
?>
修改
<?php
require("db.class.php");
$db = new DB('127.0.0.1','root','root','php3yue','set names utf8');
$res=$db->save('news',"title='刘宁'",'id=1');
if($res){
echo "修改成功";
}else{
echo "修改失败";
}
?>
查询
<?php
require("db.class.php");
$db = new DB('127.0.0.1','root','root','php3yue','set names utf8');
$arr= $db->select('news');
foreach($arr as $key=>$value){
echo $value['title'];
echo "</br>";
}
?>