2012-08-01 91 views
0

這就是這種情況。我在3個PHP文件,都在同一個項目文件夾:在PHP中使用準備好的語句時發生致命錯誤

  1. constants.php
  2. Mysql.php(類)
  3. 的index.php

當我運行的index.php,我得到:

Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\MyBlog\MyClass\MySql.php on line #

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,我得到這個:

Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\MyBlog\MyClass\MySql.php on line

這條線是:

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

欲瞭解更多信息,我測試了與數據庫的連接,沒關係。我測試了_query屬性是否採用SQL語句,並且它的確如此。

回答

0

您在這裏有一個錯字->_preparequery();

將其更改爲以下:

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

MySQL類的構造函數被命名爲__constructert();正確的構造函數名稱是__construct()

使用無效名稱,行$Db = new MySQL();創建對象,但構造函數永遠不會被調用 - 從而從不創建MySQL連接/ $conn對象。