没有框架手写php数据库连接
2021/8/6 19:06:07
本文主要是介绍没有框架手写php数据库连接,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
没有框架手写php数据库连接
```php <?php $db=new Db(); $data=$db->name('')->field('')->where()->select(); var_dump($data); $db->name('')->where([''=>2])->update(); $data=$db->name('')->field('')->where()->select(); var_dump($data); class Db{ public $hostname=''; public $username=''; public $userpwd=''; public $database=''; public $hostport=''; public $prefix='';//前缀 public $con; public $name='';//表名 public $where=''; public $field=''; public function __construct(){ $this->con=mysqli_connect($this->hostname,$this->username,$this->userpwd,$this->database,$this->hostport); if (!$this->con) { die("连接错误: " . mysqli_connect_error()); } } public function name($name){ $this->name=$this->prefix.$name; return $this; } public function where($where){ $this->where=$where; return $this; } public function get_where(){ if(empty($this->where)){ return ""; } $where=''; foreach ($this->where as $k=>$v){ $where=$where."$k=$v"; } return $where; } public function field($field){ $this->field=$field; return $this; } public function get_field(){ if(empty($this->field)){ return "*"; } return $this->field; } public function select(){ $where=$this->get_where(); $field=$this->get_field(); if(!empty($where)){ $where="where $where"; } $sql="select $field from $this->name $where"; $result = $this->con->query($sql); if ($result->num_rows > 0) { $data=[]; while($row = $result->fetch_assoc()) { $data[]=$row; } return $data; } return []; } public function find(){ $where=$this->get_where(); $field=$this->get_field(); if(!empty($where)){ $where="where $where"; } $sql="select $field from $this->name $where"; $result = $this->con->query($sql); if ($result->num_rows > 0) { $data=[]; while($row = $result->fetch_assoc()) { $data[]=$row; } return $data[0]; } return []; } public function update($data){ $where=$this->get_where(); $data_str=''; foreach ($data as $k=>$v){ $data_str=$data_str."$k=$v"; } if(!empty($where)){ $where="where $where"; } $sql="UPDATE $this->name SET $data_str $where"; return $this->con->query($sql); } }
这篇关于没有框架手写php数据库连接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-19php8的协程和hyperf的协程有什么区别?-icode9专业技术文章分享
- 2024-12-19php8 的fiber是什么?-icode9专业技术文章分享
- 2024-12-05怎么在php8,1 里面开启 debug?-icode9专业技术文章分享
- 2024-12-05怎么在php8,1 里面开启 debug?-icode9专业技术文章分享
- 2024-11-29使用PHP 将ETH账户的资产汇集到一个账户
- 2024-11-23怎么实现安卓+php 热更新方案?-icode9专业技术文章分享
- 2024-11-22PHP 中怎么实现判断多个值是否为空、null 或者为 false?-icode9专业技术文章分享
- 2024-11-11开源 PHP 商城项目 CRMEB 二次开发和部署教程
- 2024-11-09怎么使用php在kaufland平台刊登商品?-icode9专业技术文章分享
- 2024-11-05PHP的抽象类和接口是什么,有什么区别-icode9专业技术文章分享