[英]Fatal error when using a prepared statement in PHP
情況就是這樣。 我創建了3個PHP文件,都在同一個項目文件夾中:
當我運行index.php時,我得到:
致命錯誤:在第C行的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語句,而且確實如此。
類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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.