php实现的简单数据库操作Model类

高洛峰
Lepaskan: 2023-03-03 14:06:01
asal
1556 orang telah melayarinya

本文实例讲述了php实现的简单数据库操作Model类。分享给大家供大家参考,具体如下:

该数据库模型类可实现数据库的增删改查,简化数据库操作。

1. config.php代码:

<?php
 define("HOSTNAME","127.0.0.1");
 define("USERNAME","root");
 define("PASSWORD","");
 define("DATANAME","class");
Salin selepas log masuk

2. 使用代码:

<?php
 require("./config.php");
 class Model{
  private $link;
  //构造函数,初始化数据库连接
  public function __construct(){
   $this -> link = mysqli_connect(HOSTNAME,USERNAME,PASSWORD,DATANAME) or die("数据库连接失败");
   mysqli_set_charset($this -> link,"utf8");
  }
  //查找 1.表名 2.条件 3.值 如果不添加条件或者值,就全部查询
  public function find($table="",$key="",$value=""){
   if(!$key||!$value){
    $sql = "select * from {$table}";
   }else{
    $sql = "select * from {$table} where {$key} = &#39;{$value}&#39;";
   }
   $res = mysqli_query($this -> link,$sql);
   $arr = mysqli_fetch_all($res,MYSQLI_ASSOC);
   mysqli_free_result($res);
   return $arr;
  }
  //增加 1.表名 2.需要插入的字段 3.值1
  public function ins($table="",$zd="name,score",$value=""){
   $arr = explode(",",$value);
   $str = "";
   foreach($arr as $k => $v){
    $str .= "&#39;".$v."&#39;".",";
   }
   $str = rtrim($str,",");
   $sql = "insert into {$table}({$zd})values({$str})";
   $res = mysqli_query($this -> link,$sql);
   return mysqli_insert_id($this -> link);
  }
  //修改 1.表名 2.修改字段 3.值 4.条件 5.值
  public function upd($table="",$key="",$value="",$key2="",$value2=""){
   $sql = "update {$table} set {$key}=&#39;{$value}&#39; where {$key2}=&#39;{$value2}&#39;";
   $res = mysqli_query($this -> link,$sql);
   return mysqli_affected_rows($this -> link);
  }
  //删除 1.表名 2.条件 3.值
  public function del($table="",$key="",$value=""){
   $sql = "delete from {$table} where {$key}=&#39;{$value}&#39;";
   $res = mysqli_query($this -> link,$sql);
   return mysqli_affected_rows($this -> link);
  }
  //析构函数
  public function __destruct(){
   if(isset($res))
    mysqli_free_result($res);
   mysqli_close($this -> link);
  }
 }
 $m = new Model();
 //var_dump($m -> find("stu","id"));
 var_dump($m -> ins("stu","name","zhu"));
 //var_dump($m -> upd("stu","name","dujianing","id","1"));
 //var_dump($m -> del("stu","name","li"));
?>
Salin selepas log masuk

   


Label berkaitan:
php
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!