在PHP中使用预准备语句时出现致命错误

时间:2012-08-01 18:09:22

标签: php mysql prepared-statement

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

  1. constants.php
  2. Mysql.php(class)
  3. 的index.php
  4. 当我运行index.php时,我得到:

      

    致命错误:在第#

    行的C:\ wamp \ www \ MyBlog \ MyClass \ MySql.php中的非对象上调用成员函数prepare()

    constants.php:

    <?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语句,并且确实如此。

2 个答案:

答案 0 :(得分:2)

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

如果名称无效,则行$Db = new MySQL();会创建对象,但永远不会调用构造函数 - 因此永远不会创建MySQL连接/ $conn对象。

答案 1 :(得分:0)

这里有一个拼写错误->_preparequery();

将其更改为以下内容:

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