php - 是什么导致无法使用 AngularJS 和 Codeigniter 3 在 MySQL 表中插入数据?
问题描述
我正在使用Codeigniter 3.1.8和AngularJS v1.7.8开发博客应用程序。
应用程序的仪表板是“纯”Codeigniter,带有模型、控制器和视图,而前端由 AngularJS 管理和显示的 JSON 组成。
我一直无法通过 AngularJS 从前端添加评论。
我的 AngularJS 控制器如下所示:
// Post comment
.controller('PostCommentController', ['$scope', '$http', '$routeParams',
function($scope, $http, $routeParams) {
const slug = $routeParams.slug;
$http.get('api/' + slug).then(function(response) {
let post_id = response.data.post.id
$scope.newComment = {
slug: $routeParams.slug,
post_id: post_id,
name: $scope.name,
email: $scope.email,
comment: $scope.comment
};
$scope.createComment = function(){
console.log($scope.newComment);
$http.post('api/comments/create/' + post_id, $scope.newComment);
};
});
}])
我的 Codeigniter 评论控制器(在 API 内):
class Comments extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function create($post_slug){
$data = json_decode(file_get_contents('php://input'), TRUE);
$this->Comments_model->create_comment($post_id);
}
}
在Comments_model模型中,我有:
public function create_comment($post_id) {
$data = [
'post_id' => $post_id,
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment'),
'aproved' => 0,
'created_at' => date('Y-m-d H:i:s')
];
return $this->db->insert('comments', $data);
}
console.log($scope.newComment);
函数内部的line会createComment
返回一个包含所有必要“细节”的对象:
{
comment: "Test Angular",
email: "razvan_zamfir80@yahoo.com",
name: "Razvan Zamfir",
post_id: "67",
slug: "who-loves-a-butterfly"
}
然而,我收到了Failed to load resource: the server responded with a status of 500 (Internal Server Error)
这个 url 的错误:api/comments/create/67
并且 MySQL 插入语句看起来像这样(我在浏览器中的 url /api/comments/create/67 看到它):
INSERT INTO `comments` (`post_id`, `name`, `email`, `comment`, `aproved`, `created_at`) VALUES (NULL, NULL, NULL, NULL, 0, '2019-10-31 22:06:01')
我的错误在哪里?
解决方案
您需要修改 Comments_model::create_comment 方法:
public function create_comment($commentData) {
$data = [
'post_id' => $commentData['post_id'],
'name' => $commentData['name'],
'email' => $commentData['email'],
'comment' => $commentData['comment'],
'aproved' => 0,
'created_at' => date('Y-m-d H:i:s')
];
return $this->db->insert('comments', $data);
}
并使用 $data 在控制器中调用它:
public function create($post_slug){
//also you can use $data = json_decode($this->input->raw_input_stream, TRUE);
$data = json_decode(file_get_contents('php://input'), TRUE);
$this->Comments_model->create_comment($data);
}
推荐阅读
- python - 从 SQLite 数据库值返回多行
- postgresql - 索引和表大小问题
- r - 在 Shiny 中单击按钮后如何将输入保存到变量?
- javascript - 如何查看最新 Electron 版本使用的 Chromium 版本?
- reactjs - React 应用在部署到 github 页面时只显示背景颜色
- javascript - 嵌入时执行 undefined
- dialogflow-es - 在对话流中更改日期格式
- angular - Angular:强制验证模板驱动的表单
- python - (Python) Windows 中的 Tesseract 安装问题
- flutter - Flutter web - 向下滚动时淡入