2024/8/1 13:32:45 ![]()
我有三个文件分别如下:database.php:class Database { private $host = 'localhost'; private $db_name = 'db01'; private $username = 'db01'; private $password = '123456'; public $conn;
public function getConnection() { $this->conn = null; try { $this->conn = new PDO("mysql:host={$this->host};dbname={$this->db_name}", $this->username, $this->password); $this->conn->exec("set names utf8"); } catch(PDOException $exception) { echo "Connection error: " . $exception->getMessage(); } return $this->conn; }}
index.php:header("Access-Control-Allow-Origin: *");header("Content-Type: application/json; charset=UTF-8");
require_once 'api/database.php';
// Instantiate database$database = new Database();global $db;$db = $database->getConnection();
// Route requests based on the URL$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));switch ($request[0]) { case 'users': include 'api/users.php'; break; case 'classes': include 'api/classes.php'; break; case 'courses': include 'api/courses.php'; break; case 'videos': include 'api/videos.php'; break; case 'tests': include 'api/tests.php'; break; case 'comments': include 'api/comments.php'; break; default: http_response_code(404); echo json_encode(array("message" => "Endpoint Not Found.")); break;}
users.php:
// Database configuration// $servername = "localhost"; // 数据库服务器地址// $username = "db01"; // 数据库用户名// $password = "123456"; // 数据库密码// $dbname = "db01"; // 数据库名称// $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { $query = "SELECT * FROM users"; $stmt = $db->prepare($query); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($users);}如果把users.php的注释取消,用postman访问http://localhost/api/users.php一切正常,但是现在这个情况程序是会报错的,报错信息如下:Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\phpstudy_pro\WWW\project\api\users.php:14 Stack trace: #0 {main} thrown in C:\phpstudy_pro\WWW\project\api\users.php on line 14
请帮我检查三个文件,我改如何修改代码来解决现在的问题?2024/8/1 13:32:45 
出现这个错误的原因是因为在 `users.php` 中 `$db` 变量没有被正确初始化。虽然你在 `index.php` 中初始化了 `$db` 变量,但这个变量并没有在 `users.php` 中被引用。
解决这个问题的一种方法是将 `users.php` 中对 `$db` 变量的引用改成全局变量。具体来说,可以在 `users.php` 中添加对 `$db` 变量的全局引用。
以下是修改后的 `users.php`:
```php
global $db; // 添加这一行来引用全局变量
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { $query = "SELECT * FROM users"; $stmt = $db->prepare($query); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($users);}```
同时确保你是通过 `index.php` 入口访问 API,比如使用 `http://localhost/project/index.php/users` 而不是直接访问 `users.php`。因为直接访问 `users.php` 会跳过 `index.php` 对数据库连接的初始化,这也是造成错误的原因之一。
### 总结1. 在 `users.php` 中添加 `global $db;` 来引用全局的数据库连接变量。2. 确保通过 `index.php` 入口来访问 API(例如:`http://localhost/project/index.php/users`)。
这样修改后,应该就能正常通过 `index.php` 入口访问并使用数据库连接了。