【问题标题】:Fatal error when using a prepared statement in PHP在 PHP 中使用准备好的语句时出现致命错误
【发布时间】:2012-08-01 18:09:21
【问题描述】:

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

  1. constants.php
  2. Mysql.php(类)
  3. index.php

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

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

常量.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 语句,它确实接受了。

【问题讨论】:

    标签: php mysql prepared-statement


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你在这里打错了-&gt;_preparequery();

      将其更改为以下内容:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-15
        • 2015-10-28
        • 1970-01-01
        • 2021-04-10
        相关资源
        最近更新 更多