我的PHP代码有问题,我已经阅读了很多答案,但我找不到答案。 我有两个文件:db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/config.php';
// Connecting to mysql database
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Selecing database
$mysqli ->select_db(DB_DATABASE);
// returing connection cursor
return $mysqli;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
$mysqli->close();
}
}
?>
和get_courses_details.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = $db -> query("SELECT * FROM corsi");
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["corsi"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$corsi = array();
$corsi ["corso_id"] = $row["corso_id"];
$corsi ["corso_nome"] = $row["corso_nome"];
// push single product into final response array
array_push($response["corsi"], $corsi);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No courses found";
// echo no users JSON
echo json_encode($response);
}
?>
但是当我尝试运行它时显示以下消息: 致命错误:在第19行的get_courses_details.php中调用未定义的方法DB_CONNECT :: query()
你知道我该如何解决它吗?
答案 0 :(得分:0)
您正在使用$db = new DB_CONNECT();
制作新的类对象。然后,在您尝试运行$result = $db -> query("SELECT * FROM corsi");
之后,但返回语法错误,因为类对象中没有方法query()
。
您要做的是创建一个公共属性并在connect()
方法中定义它,例如:
class DB_CONNECT {
public $sth;
...
public function connect() {
...
$this->sth = $mysqli;
}
}
现在您可以使用$db->sth->query()
,因为$db->sth
现在是您的MySQL对象。