php - 如何更新mysql数据库中存储的数据

标签 php mysql database

我有一个网页,用户可以在其中“添加”帖子或“更新”现有帖子。在下面的代码中,我的“添加”功能完全可以正常添加新帖子。但是,我的“更新”功能根本不起作用。它无法更新我的数据库中的现有帖子。谁能帮助我我做错了什么?谢谢!!

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/

相关文章:

php - 从逗号分隔字段创建数组

mysql - 数据库的差异

mysql - Oracle DB,mysql不能做什么?

mysql - 如何从别名查找mysql中的总计(总和)?

sql - 使用和不使用连接的查询性能

javascript - 将数据从 jQuery Ajax 传递到 PHP 并将这些值保存在数据库中

php - 如何在jquery Fancy Box Pop up中使用渲染 View

MySQL 在行不处于特定状态时获取时间

PHP/MySQL 数据不转到 mysql

php - Laravel Advanced Wheres 如何将变量传递给函数?