【问题标题】:mysql query works sometimes but not alwaysmysql查询有时但并非总是有效
【发布时间】:2026-01-25 18:40:01
【问题描述】:

我正在构建一个简单的“小”电影编目数据库系统供我自己使用。现在的问题是我有一个 mySQL 查询在大多数情况下都有效,但不是全部。基本上它通过使用第 3 方 IMDB API 来工作。我用它来搜索和提取我需要的值,效果很好。它显示在我的预览屏幕和所有内容上。我遇到的问题是,虽然大多数电影都能正常播放,但有一些不能,我无法弄清楚原因。

例如,The Fellowship of the Ring 存储得很好,而 The Return of the King 根本不会通过查询。我找不到任何差异。

这是我的查询:

    $query = "INSERT INTO movies
(title, year, releaseDate, actors, image, runtime, genre, director, rating, watchedDate, category, series, comments, owned, ownedFormat, seen, plot, favorite, uploadDate)
VALUES ('$title', '$year', '$releaseDate', '$actors', '$newImg', '$runtime', '$genre', '$director', '$rating', '$watchedDate', '$category', '$series', '$comments', '$owned', '$ownedFormat', '$seen', '$plot', '$favorite', '$curDate')";

    mysql_query($query) or die ('Error');

我不确定我还需要提供什么。似乎电影中的某种差异导致了错误,但我不知道。

谢谢!

** 编辑 ***

所以我尝试切换到 mysqli。这是我的新代码:

    /* Create the prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO movies (title, year, releaseDate, actors, image, runtime, genre, director, rating, watchedDate, category, series, comments, owned, ownedFormat, seen, plot, favorite, uploadDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) {

    /* Bind our params */
    $stmt->bind_param('sssssssssssssssssis', $title, $year, $releaseDate, $actors, $newImg, $runtime, $genre, $director, $rating, $watchedDate, $category, $series, $comments, $owned, $ownedFormat, $seen, $plot, $favorite, $curDate);

    /* Execute the prepared Statement */
    $stmt->execute();

    /* Echo results */
    echo "Inserted {$title} into database\n";
}

但是,现在我收到一条错误消息: 致命错误:在 if 语句开始的行上的非对象上调用成员函数 prepare()。

我假设这是因为我的查询不是对象?

谢谢

【问题讨论】:

  • 看起来不像是在清理输入变量。如果说 $title 是“不起作用”,您的查询将因为 '.还要粘贴您使用 mysql_error() 得到的 mysql 错误
  • 您是否正确地使用mysql_real_escape_string 转义了值?

标签: php mysql database


【解决方案1】:

最可能的原因是您将原始值放在单引号之间。如果其中一个值包含单引号,则会出现语法错误。

更好的方法是绑定参数。你可以阅读更多关于here的信息。

【讨论】:

    【解决方案2】:

    如果没有关于实际返回值的更多信息,很难说。返回值可能包含破坏代码的字符,例如分号或引号。尝试使用正则表达式去除所有非字母数字字符。

    $result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);
    

    你有一个 sql 注入漏洞。考虑使用 PDO 代替已弃用的 mysql 函数。

    http://php.net/manual/en/book.pdo.php

    【讨论】:

    • 我会试试的。至于漏洞,我完全清楚。但是,它仅供个人使用,不会被利用。
    最近更新 更多