无法用我的班级连接到数据库?

时间:2017-03-16 06:37:12

标签: php mysql

我正在尝试连接到我的数据库,但它无法连接。我尝试但不会连接。我得到的错误是Parse错误:语法错误,第3行的C:\ htdocs \ www \ dating \ index.php中的意外'连接'(T_STRING)。我调用了试过的新数据库connect();并试过connect();我收到此消息致命错误:在第3行的C:\ htdocs \ www \ dating \ index.php中调用未定义的函数connect()。出了什么问题?

class Database{
private $db_host = "localhost";
private $db_user = "123346";
private $db_pass = "12345";
private $db_name =  "1234";
public  $conn;
// Create connection
public function connect(){
    if(!isset($this->conn)){
        $this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);

        if($this->conn){
            $this->conn = true;
            return true;
        }else{
            $this->conn = false;
            return false;
        }
    }
}
public function disconnect(){
    if(isset($this->conn)){
        if(mysqli_close($this->conn)){
            $this->myconn = false; 
            echo "connection closed";
            return true; 
        } else{
            echo "failed to close connection";
            return false; 
            }
        }else{
        echo "no connection prescent";
        }
    }

}

我正在尝试使用查询,但它不会得到结果。这是代码

 include("functions/connect.php");
 $db = new Database("localhost", "12345", "1234", "123");
 $db->connectdb();
 $db->select('rpg');


/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT id, username FROM users ORDER by ID DESC ";



if ($result = $db->query($query)) {

/* fetch object array */
while ($row = $result->fetch_row()) {
    printf ("%s (%s)\n", $row[0], $row[1]);
}

/* free result set */
$result->close();
}
 /* close connection */
$db->close();`

1 个答案:

答案 0 :(得分:1)

请更改此行

  private _myFieldInComponentClass:String;
  set myFieldInComponentClass(value :String) {
    this._myFieldInComponentClass = value;
    // other code
  }
  get myFieldInComponentClass() {
    return this._myFieldInComponentClass;
  }

到这个

$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);

您会注意到您使用了$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name); 但它应该是$this->pass

要调用Database类的函数,你必须编写这样的代码;

$this->db_pass