没有框架手写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-03-29env: php: no such file or directory
- 2024-03-01php foreach break
- 2024-02-26Exception参数 php-icode9专业技术文章分享
- 2023-12-30PHP文件批量上传-icode9专业技术文章分享
- 2023-12-30thinkphp6 withJoin-icode9专业技术文章分享
- 2023-12-27MagicArray:像php一样,让Go业务代码不再卷!
- 2023-11-18centos7编译安装PHP教程。
- 2023-11-18centos7编译安装phpMyAdmin教程。
- 2023-10-13唱衰这么多年,PHP 仍然还是你大爷!
- 2023-07-25PHP8,性能更好,语法更好,类型安全更完善