所以,目前,我正在开发一个用于教育目的的简单 PHP 框架(如 Laravel),并且一切正常,除了我的一个数据库方法(负责将数据插入数据库的方法)实际上没有插入任何数据,更奇怪的是它没有显示任何错误,这就是为什么我现在很困惑。
这是我的插入方法:
// Create a method to insert data into a table
public function insert($table, $data): bool
{
try {
// Prepare the query using named parameters
$sql = "INSERT INTO $table (";
foreach ($data as $key => $value) {
$sql .= "$key, ";
}
$sql = rtrim($sql, ", ");
$sql .= ") VALUES (";
foreach ($data as $key => $value) {
$sql .= ":$key, ";
}
$sql = rtrim($sql, ", ");
$sql .= ")";
$stmt = $this->conn->prepare($sql);
// Bind the values to the parameters
foreach ($data as $key => $value) {
$stmt->bindValue(":$key", $value);
}
// Execute the query and return the result
return $stmt->execute();
} catch (PDOException $e) {
Exception::throw(PDOException::class, $e->getMessage());
}
}
这是我的控制器中调用插入方法的创建方法:
// Route: Method=GET & URI=localhost/users/create
public static function newUser(): void
{
// This view contains a form for creating a new user
Response::view('Users/user.create');
}
// Route: Method=POST & URI=localhost/users/create
public static function create(): void
{
Database::getConnection()->insert('users', [
'username' => $_POST['username'],
'email' => $_POST['email']
]);
// Redirect to the previous view with a success message after inserting data
Response::view('Users/user.create', [
'msg' => 'User successfully created!'
]);
}
当我在表单中输入数据并提交时,它实际上将我重定向回之前的视图并显示成功消息,但是当我使用 Phpmyadmin 检查我的数据库时,没有任何内容插入我的数据库。
我已经尝试检查插入方法并确保正确生成了 sql 查询,但它仍然没有将任何数据插入数据库