创建一个PHP类来处理数据库连接但是收到错误

时间:2018-04-17 01:24:42

标签: php class

我已经在PHP中创建了一个用于连接到数据库并从中选择信息的类。这是代码:

<?php

  /* this script is for creating a class to connect to the database */

  include "includes/config.php";

  class database {
    protected static $connection; // variable to hold the mysqli connection


    protected function connect(){
      if (!isset(self::$connection)){
        self::$connection = new mysqli(SERVER_NAME, USERNAME, PASSWORD, DB_NAME);
      }
      if (self::$connection === false){ //in case connection failed return false
        return false;
      }
      else {
        return self::$connection; // returns the connection 
      }
    }


    protected function query($query){ // public function to take a sql query
      $connection = $this->connect(); // calls the connect function to create a connection to the database
      $result = $connection->query($query); // puts the query into the result variable
      return $result; //returns the result
    }


    public function select($query){
      $rows = new array();
      $result = $this->query($query);
      if($result === false){
        return false;
      }
      while($row = $result->fetch_assoc()){
        $rows[] = $row;
      }
      return $rows;
    }


    public function error(){
      $connection = this->connect();
      return $connection->error;
    }
  }

?> 

错误发生在select函数之前的行上,奇怪地没有代码,但错误说的是错误。这是确切的错误。

  

解析错误:语法错误,意外&#39;数组&#39; (T_ARRAY)在第31行的C:\ wamp64 \ www \ final \ includes \ connect.php

有人能发现错误吗?

1 个答案:

答案 0 :(得分:0)

  • 函数select($query)上存在语法错误:
    $rows = array();代替new array();

  • 函数error()上的
  • ,应为$connection = $this->connect(),尽量不要忘记$符号。