【发布时间】:2019-07-26 17:43:56
【问题描述】:
我正在创建一个内部知识库,我正在努力使用 PHP 成功创建新的数据库条目。
为了使用这个功能,我创建了几个文件:
-
* config.php,连接数据库;
- * post.php,显示帖子;
- * post_list.php,显示帖子列表并允许重定向到post.php?id=x,其中x是数据库中每个帖子的id;
- * post_handler.php,它处理每个帖子,创建或更新条目;
- * post_controller.php,这是一个Post类,具有多种功能:通过id获取某个post; getAll 获取所有帖子以显示在 post_list 中;创建和更新帖子;
- * post_editor.php,这是一个编辑器,如果我正在编辑一个帖子,它会获取特定的帖子信息;如果我想创建一个帖子,它是一个空白编辑器。
我在 MySQL 表中手动创建了条目来测试以前的文件,并且我可以成功查看和编辑帖子,但是当我尝试创建一个新条目时,它在调用 post_handler.php 时出现错误 500,我不明白为什么。
为了简单起见,因为其他函数也可以工作,我将展示在 Post 类 (post_controller.php) 中创建帖子的函数:
static $dbh;
static function create ($post) {
$sql = "INSERT INTO mydb.Posts (title, body) values (?.?)";
$stmt = self::$dbh -> prepare($sql);
if ($stmt){
$stmt -> bindValue(1, $post["title"]);
$stmt -> bindValue(2, $post["body"]);
return $stmt -> execute();
}
}
这里是 post handler.php:
require_once("config.php");
require_once("post_controller.php");
if (!empty($_POST["id"])) {
// update
if (Post::update($_POST)) {
echo "Successfully updated";
} else {
header("HTTP/1.0 500 Internal error");
echo "Couldn't update";
}
} else {
// create
if (Post::create($_POST)) {
echo "Successfully created new article";
header ("Location: index.php");
} else {
header("HTTP/1.0 500 Internal error");
echo "Couldn't create new article";
}
}
这是在 post_editor.php 中提交表单的 AJAX 脚本:
$id = ($_GET["id"]);
if ($id) {
$post = Post::get((int) $id);
}
// submit the form, delegation
$(document).on("submit", "form#form", function(event){
event.preventDefault();
var data = $("#form").serialize();
$.ajax({
url: "post_handler.php",
data: data,
type: "post",
success: function (response) {
// if the request is successful
alert(response);
},
error: function (xhr) {
// if the request is not successful
alert(xhr.responseText);
}
});
});
我不明白为什么更新帖子可以正常工作,但我无法使用此代码创建新条目。当我尝试提交新帖子时,警报文本框显示为空白,而在更新时它会提示正确的“成功更新”消息。
我做错了什么?
谢谢。
【问题讨论】:
-
点是错字吗?
values (?.?) -
是的。我修好了,谢谢!现在它工作正常。