我知道之前曾问过类似的问题,但没有与像这样的ajax一起问过... 因此,我尝试了对数据库类进行依赖注入,并使用红色指南(例如https://phpdelusions.net/pdo/common_mistakes)声明应该建立数据库的一个连接实例并将其传递给所有类/函数...
问题是,当我使用ajax从Index.php到myfunctions.php进行发布时,该怎么办...我认为问题出在这里:
$database = new Database();
$conn = $database->getConnection();
我是否可以在Database.php中实例化它都没有关系,因为即使我有“ require_once”,每个ajax调用也会运行它...(通过简单的测试进行验证,以从Database类的构造函数中打印出日志消息)
Database.php
<?php
class Database
{
private $host = "";
private $db_name = "";
private $username = "";
private $password = "";
private $conn;
function __construct()
{
$this->host = "localhost";
$this->db_name = "mydb";
$this->username = "user";
$this->password = "pass";
}
public function getConnection()
{
$this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->db_name);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $this->conn;
}
}
?>
Index.php
<?php
header("Access-Control-Allow-Origin: *");
// start session, and check for valid login
?>
<!DOCTYPE html>
<html>
// all HTML including bind jquery ajax calls to functions.php
$.ajax({ method: "POST", url: "myfunctions.php", }) ... and so on
MyFunctions.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once "database.php";
$database = new Database();
$conn = $database->getConnection();
MyFunctions::start();
class MyFunctions
{
public static function start()
{
// Do stuff...
$stmt = $conn... // and so on
}
//....