在PHP中使用prepared语句时出现致命错误


Fatal error when using a prepared statement in PHP

情况就是这样。我创建了3个PHP文件,都在同一个项目文件夹中:

  1. 常量.php
  2. Mysql.php(类)
  3. index.php

当我运行index.php时,我得到:

致命错误:在C:''wamp''www''MyBlog''MyClass''MySql.php的#行对非对象调用成员函数prepare()

constants.hp:

<?php
//Define constent her
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'myblog');

Mysql.php:

<?php 
require_once 'constants.php';
class MySql{
        private $conn;
        protected $_query;
    function __constructert() {
        $this->conn = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or
        die("There was a probelm connecting the database");
        return $this->conn;
    }
    protected function _prepareQuery() 
   {
//her the line that problem come from beetwen the () of if : 
      if (!$stmt = $this->conn->prepare($this->_query)) {
         trigger_error("Problem preparing query", E_USER_ERROR);
      }
      return $stmt;
   }
    protected function _dynamicBindResults($stmt){
        $meta=$stmt->result_metadata();
        while ($field = $meta->fetch_field()) {
            print_r($field);
        }
    }
    function query($query){
        $this->_query = filter_var($query,FILTER_SANITIZE_STRING);
        $stmt = $this->_preparequery();
        $stmt->execute();
        $results=$this->_dynamicBindResults($stmt);
    }

index.php:

<? PHP
        include 'MySql.php';
        $Db= new MySql();
        $Db->query("select * from status");

正如我所说,当我运行index.php时,我得到的是:

致命错误:在行对C:''wamp''www''MyBlog''MyClass''MySql.php中的非对象调用成员函数prepare()

那条线是:

if (!$stmt = $this->conn->prepare($this->_query)) {

为了了解更多信息,我测试了与数据库的连接,一切正常。我测试了_query属性是否接受SQL语句,它确实接受了。

MySQL的构造函数名为__constructert();正确的构造函数名称是__construct()

使用无效名称,行$Db = new MySQL();创建对象,但从未调用构造函数,因此从未创建MySQL连接/$conn对象。

您在这里有一个打字错误->_preparequery();

将其更改为以下内容:

function query($query){         
  $this->_query = filter_var($query,FILTER_SANITIZE_STRING);         
  $stmt = $this->_prepareQuery();         
  $stmt->execute();         
  $results=$this->_dynamicBindResults($stmt);     
}