本文介绍了使用php pdo更新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用PDO并不陌生,我可以通过添加和删除条目来完成所有这些工作,但是我无法使用它来更新数据.我不确定我的sql语句是否已关闭,或者我是否仅在此处缺少某些内容.

I'm new to using PDO and I got all this to work with adding and deleting entries, but I can't get it to update data. I'm not sure if my sql statement is off or if I'm just missing something here.

if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $data = $article->fetch_data($id);

    if(isset($_POST['title'], $_POST['content'])) {
        $title = $_POST['title'];
        $content = nl2br($_POST['content']);

        if (empty($title) or empty($content)) {
            $error = 'All fields are required!';
        } else {
            $query = $pdo->prepare('UPDATE articles SET article_title = ?, article_content = ?, article_timestamp = ? WHERE article_id = $id');

            $query->bindValue(1, $title);
            $query->bindValue(2, $content);
            $query->bindValue(3, time());

            $query->execute();

            header('Location: index.php');
        }
    }
}

推荐答案

您需要对查询加双引号以对$ id变量进行插值.如果使用单引号,则变量将被解释为$ id.

You need to double quote your query to interpolate the $id variable. If you use single quotes your variables will be interpreted as $id.

$query = $pdo->prepare("UPDATE articles SET article_title = ?, article_content = ?, article_timestamp = ? WHERE article_id = $id");

正如其他人所说,这可能导致SQL注入.

As others have said this can lead to SQL injection.

相反,您还应该绑定$ id变量:如果将int用作ID,则可能还需要使用PDO::PARAM_INT.示例$query->bindValue(4, $id, PDO::PARAM_INT);

Instead you should also bind the $id variable: If you are using an int as your id you may also want to use PDO::PARAM_INT. Example $query->bindValue(4, $id, PDO::PARAM_INT);

$query = $pdo->prepare("UPDATE articles SET article_title = ?, article_content = ?,

article_timestamp = ? WHERE article_id = ?");
$query->execute(array($title, $content, time(), $id));

这篇关于使用php pdo更新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:37