【问题标题】:php - update query i get error when i use in variables [duplicate]php - 更新查询我在变量中使用时出错[重复]
【发布时间】:2018-11-17 02:28:43
【问题描述】:

我尝试更新我的数据库,但出现错误。

我在mysql中有一个表:

article_id article_title article_content article_timestamp img_url

在我的代码中:

if(isset($_SESSION['logged_in'])) {
// display add page
if(isset($_POST['title'], $_POST['content'])) {
    $title = $_POST['title'];
    $content = nl2br($_POST['content']); // nl2br - Inserts HTML line breaks 
 before all newlines in a string
    $image = $_POST['image'];
    //$image = "admin/uploads/" . $_FILES['image']['name'];
    $id = $_POST['article_id'];

    if(empty($title) OR empty($content)) {
        $error = 'All fields are required';
    } else {
        **$query = $pdo->prepare("UPDATE articles SET article_title =  $title, 
article_content =  $content, img_url =   $image  WHERE article_id=$id");**
        $query->execute();

        header('Location: index.php');

    }

}
?>

...

我尝试写一个变量,但我得到错误,为什么?

谢谢...

【问题讨论】:

  • 你的意思是你得到了由 if(empty($title) OR empty($content)) 触发的错误还是一个实际的错误?如果 PHP 抛出错误,请将其包含在帖子中

标签: php mysql forms session


【解决方案1】:

虽然您的问题还不清楚,但 @Steve 建议您收到什么样的错误。在准备好的语句之后,您没有绑定变量。我建议阅读Pdo prepare

一个简单的例子:

$stmt = $pdo->prepare('UPDATE articles SET article_title =  ?, article_content =  ?, img_url = ?  WHERE article_id = ?');
$stmt->execute(array($title, $content, $image, $id));
$user = $stmt->fetch();

【讨论】:

  • 虽然这是一个可能的解决方案,但它并没有解释为什么他们的代码一开始就失败了。
  • 另外,如果他们的 PHP 版本不支持 [] 数组方法,您发布的内容将使他们失败。参考:php.net/manual/en/language.types.array.php
  • 你在阵列上得到了一个很好的观点。我做了一个快速编辑。
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 2021-01-09
  • 2021-10-27
  • 2015-09-24
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多