没有框架手写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数据库连接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程