运行PHP代码时出现以下错误。
Call to a member function query() on null
以下是代码,
function fetch_url($url_code) {
$query = "SELECT * FROM `urls` WHERE `url_code` = ? ";
$result = $this->db->query($query, array($url_code));
if ($result) {
return $result;
} else {
return false;
}
}
请指导我如何删除此错误。
答案 0 :(得分:2)
this->db->query
函数只需要SQL代码。不喜欢PDO。
确保已加载库
在config/autoload.php
中添加此$autoload['libraries'] = array('database');
试试这个
function fetch_url($url_code) {
$query = $this->db->query("SELECT * FROM urls WHERE url_code = '$url_code' ");
$result = $query->result_array(); # setting array to objective
$count = count($result); # get count
if (!empty($count)) {
return $result;
}
else {
return false;
}
}
答案 1 :(得分:2)
您的$this->db
为空。请确保在致电query
之前已正确初始化。这是MySQL的一个非常基本的例子(你必须使它适应你的数据库系统):
function init() {
$this->db = new mysqli('host', 'user', 'password', 'database');
if (!$this->db) {
die('MySQL Connection Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
function fetch_url($url_code) {
$sql = "SELECT * FROM urls WHERE url_code = '$url_code' ";
if ($this->db === null) {
$this->init();
}
$query = $this->db->query($sql);
$result = $query->result_array(); # setting array to objective
$count = count($result); # get count
if (!empty($count)) {
return $result;
}
else {
return false;
}
}
答案 2 :(得分:0)
class Database {
public $host=DB_HOST; // Specify localhost
public $username=DB_USER; //Specify username
public $password=DB_PASSWORD; // specify password
public $dbname=DB_NAME; // specify database name
public $conn ;
public $error;
/*
* Class Constructor
*/
Public function __constructor() {
// Call Connect Function
$this->connect();
}
/*
* Connector
*/
Public function connect() {
//* Creating mySqli Class Object * //
$this->conn = new mysqli($this->host,$this->username,$this->password,$this->dbname);
if (!$this->conn) {
$this->error = "Connection failed :" .$conn->connect_error ;
return false;
}
}
/*
* Select function
*/
public function select($query) {
/* to avoid call to member function query() on Null Error
Use this 2 lines of code */
if ($this->conn === null) {
$this->connect();
}
$results = $this->conn->query($query) or die($this->conn->error.__LINE__);
/* If there is atleast one row in the table Condition is true / Return table Rows as per your sql query */
if($results->num_rows > 0) {
return $results;
}
else {
return false;
}
} //Select Function Ends;
} //Class ends here ..
答案 3 :(得分:-1)
是使用这行代码来摆脱错误调用PHP中的null调用成员函数query()我在我的数据库类中使用它并且它工作正常!