面向对象数据库

来源:互联网 发布:怎样做淘宝详情页 编辑:程序博客网 时间:2024/05/16 08:22

<?php

 //定义封装的类:公共的数据库类
 class MySQL{
 private $host;//主机
 private $name;//用户名
 private $pass;//密码
 private $database;//数据库
 private $charset;//编码
 private $conn;//连接
 //用set get函数
 function __set($n,$v){
  $this->$n=$v;
 }
 function __get($n){
  return $this->$n;
 }
 //构造函数赋值
 function __construct($host,$name,$pass,$db,$cs){
  $this->host=$host;
  $this->name=$name;
  $this->pass=$pass;
  $this->database=$db;
  $this->charset=$cs;
  $this->conn=$this->getConn();
 }
 //得到链接
  function getConn(){
   $conn =  mysql_connect($this->host,$this->name,$this->pass) or die("连接失败");
  mysql_select_db($this->database,$conn) or die("失败");
  mysql_query("set names '$this->charset'");
  return $conn;
  }

 function myUpdate($sql){
  $res = mysql_query($sql,$this->conn) or die(mysql_error());
  if($res>0){
   echo "成功";
  }else{
   echo "失败";
  }
  return $res;
 }

 function myFetch($result){
  $row = mysql_fetch_array($result);
  return $row;
 }


 }

 

?>
<?php

include("08MySQL.php");
//创建mysql对象
$mysql = new MySQL("localhost","root","123456","think_frank","gbk");
//添加
$addSQL = "insert into think_blog(title,content) values('08网络','马上毕业了')";
$mysql->myUpdate($addSQL);


//删除
//$delSQL = "delete from  think_blog where id=19";
//$result = $mysql->myUpdate($delSQL);
//echo $result;
//修改
//$upSQL = "update think_blog set title='网络信息' ,content='呃呃呃呃呃呃' where id=24";
//$r = $mysql->myUpdate($upSQL);
//echo $r;
//查询单条记录
$sql="select * from think_blog where id=16";
$res = $mysql->myUpdate($sql);
//需要对结果做遍历
if($row = $mysql->myFetch($res)){
 echo $row[0].",".$row[1].",".$row[2]."<br/>";
}
////查询所有记录
$allSQL = "select * from think_blog";
$resall = $mysql->myUpdate($allSQL);
while($row = $mysql->myFetch($resall)){
 echo $row[id].",".$row[title].",".$row[content]."<br/>";
}

 

?>

0 0