我有一个网页,用户可以在其中“添加”帖子或“更新”现有帖子。在下面的代码中,我的“添加”功能完全可以正常添加新帖子。但是,我的“更新”功能根本不起作用。它无法更新我的数据库中的现有帖子。谁能帮助我我做错了什么?谢谢!!
class ShareModel extends Model{
public function Index(){
$this->query('SELECT * FROM shares ORDER BY create_date DESC');
$rows = $this->resultSet();
return $rows;
}
public function add(){
// Sanitize POST
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if($post['submit']){
if($post['title'] == '' || $post['body'] == '' || $post['link'] ==''){
Messages::setMsg('Please Fill In All Fields', 'error');
return;
}
// Insert into MySQL
$this->query('INSERT INTO shares (title, body, link, user_id) VALUES(:title, :body, :link, :user_id)');
$this->bind(':title', $post['title']);
$this->bind(':body', $post['body']);
$this->bind(':link', $post['link']);
$this->bind(':user_id', 1);
$this->execute();
// Verify
if($this->lastInsertId()){
// Redirect
header('Location: '.ROOT_URL.'shares');
}
}
return;
}
public function update(){
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if($post['update']){
if($post['title'] == '' || $post['body'] == '' || $post['link'] ==''){
Messages::setMsg('Please Fill In All Fields', 'error');
return;
}
$title = $post['title'];
$body = $post['body'];
$link = $post['link'];
// Update MySQL
$this->query('UPDATE shares SET (title, body, link, user_id) VALUES(:title, :body, :link, :user_id) ' );
$this->bind(':title', $post['title']);
$this->bind(':body', $post['body']);
$this->bind(':link', $post['link']);
$this->bind(':user_id', 1);
$this->execute();
header('Location: '.ROOT_URL.'shares');
}
return;
}
}
最佳答案
您的更新语法已关闭。 MySQL 的更新语法(也是大多数其他数据库使用的语法)是:
UPDATE some_table
SET col1 = val1, col2 = val2, ...
也就是说,直接使用equals为每一列分配一个更新值。试试这个版本:
$this->query('UPDATE shares SET title = :title, body = :body, link = :link, user_id = :user_id');
编辑:大多数时候,您还会有一个包含更新的 WHERE
子句,除非您确实打算更新表的每条记录。
关于php - 如何更新mysql数据库中存储的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51763030/