PHP连接数据库---博客园老牛大讲堂

  PHP是什么:PHP其实类似于Java语言,PHP就是面向对象的语言。PHP也有页面(页面是.php文件),也有后台(也是.php文件)。---博客园老牛大讲堂

       介绍:下面我实现数据库的连接,并实现数据的查询。

       开发环境:​HBuilder+xampp-control

       ​环境:MySQL数据库连接名:localhost;

                连接用户名:root;

                连接密码:root;

                数据库名字:baixingwang;

                数据库表名字:goods;

  工作目录

   

​     1、config.php文件

<?php
    define("DB_HOST","localhost");
    define("DB_USER","root");
    define("DB_PASSWORD","yilin");
    define("DB_NAME","phpwenjian");
?>
config.php

  2、connec.php文件

<?php
    include "../config/config.php";
    class DBConnect{
        protected $conn;
        public function  __construct(){
            $this->conn=new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
            if(!$this->conn){
                die("error:"+$this->conn->connect_error);
            }
            $this->conn->query("SET NAMES UTF8");
        }
        public function __destruct(){
            $this->conn->close();
        }
    }
?>
connec.php

  3、Dao.php文件

<?php
    include "../Util/connec.php";
    class DB extends DBConnect{
        public function SelectAll(){
            $result=$this->conn->query("SELECT * from chapters");
            $myArry=array();
            while($row=$result->fetch_array()){
                $myArry[]=$row;
            }
            return $myArry;
        }
    }
?>
Dao.php

  4、Server.php文件

<?php
    include "../Dao/Dao.php";
    $db=new DB();
    echo json_encode($db->SelectAll());
?>
Server.php

  5、常见错误:

     错误原因:原因是​因为文件含有中文,所以把中文改为英文就行了。

原文地址:https://www.cnblogs.com/laonniudajiangtang/p/5855522.html