php链接数据库简单基础流程

<?php 
    class Mysql {
        private $mysqli;
        private $host =     'localhost';
        private $username = 'root';
        private $password = 'root';
        private $datebase = 'shop';
        public function __construct(){
            $this->con();
        }
        public function con (){
            $this->mysqli = mysqli_connect($this->host,$this->username,$this->password,$this->datebase) or die('fdfd'.mysqli_connect_errno());
            
            $this->mysqli->query('set names utf8');
        }
        //单条数据查询
        public function getRow($sql){
            return $this->mysqli->query($sql)->fetch_assoc();
        }
        /**
         * 多条查询
         */
        public function getAll($sql){
            $obj = $this->mysqli->query($sql);
            $arr = array();
            while($row=$obj->fetch_assoc()){
                $arr[] = $row;
            }
            return $arr;
        }
        /**
         * 插入和更新数据
         */
        public function exc ($table,$data,$action="insert",$where = 0){
            if($action == 'insert'){
                $sql = "insert into ".$table." (";
                $sql.=implode(',',array_keys($data)).") values ('";
                $sql.=implode("','",array_values($data))."')";
                // var_dump($sql);die;
                return $this->mysqli->query($sql);
            }else{
                $sql = "update ".$table." set ";
                foreach ($data as $k => $val) {
                    $sql.=$k."='".$val."',";
                }
                $sql = trim($sql,',');
                $sql.=" where ".$where;
                return $this->mysqli->query($sql);
            }
        }

        public function getLastId(){
            return $this->mysqli->insert_id;
        }
    }


    $hua = new Mysql();
     // $sql = "select a.content,b.username from comment as a left join user as b on a.name_id = b.sex";
    $data=array(
        'content' => 'jjjjj',
        'aid'     => 2,
        'name_id' => 24
    );
    // var_dump(implode(',',array_values($data)));die;
    var_dump($hua->exc('comment',$data));

    print_r($hua->getLastId());
?>

 

posted on 2018-05-31 17:41  泽一年  阅读(195)  评论(0编辑  收藏  举报

导航