【问题标题】:How to fix that stmt->execute() always returns false?如何修复 stmt->execute() 总是返回 false?
【发布时间】:2017-06-11 08:46:20
【问题描述】:

我正在开发一个带有数据库的 php 项目。我希望用户能够评论文章(我已经有一个用于创建文章的工作系统),但我无法在数据库中插入 cmets。代码如下:

  if ($_SERVER["REQUEST_METHOD"] == "POST") {
$content = filter_input(INPUT_POST, 'new_entry', FILTER_SANITIZE_STRING);
$author = $_SESSION["username"];
$article_id = $_GET['article'];
$rating = 0;

if ($insert_stmt = $mysqli->prepare("INSERT INTO `entries` (`article_id`, `rating`, `content`, `author`) VALUES (?, ?, ?, ?)")) {
    $insert_stmt->bind_param('iiss', $article_id, $rating, $content, $author);
    // Führe die vorbereitete Anfrage aus.
    if ($insert_stmt->execute()) {
        header('Location: success.php');
    } else {
      header('Location: failure.php');
    }
}

这总是将我引导到“failure.php”——这里有什么问题?

提前谢谢你!

【问题讨论】:

  • 我建议您查看您的 http 服务器错误日志文件并使用 mysqli 类提供的错误处理功能。
  • 我收到此错误:PHP Notice: Undefined index: article in C:\MAMP\htdocs\index.php on line 30
  • article 是从查询字符串传递过来的吗?或者您可能需要使用 POST :$article_id = $_POST['article'];
  • @b. desai articlelocalhost/index.php?article=5 这样写在 url 中,但 $_GET['article'] 总是返回 null。

标签: php mysql pdo


【解决方案1】:

因为你有,

$article_id = $_GET['article'];

在您的代码中,当您发布表单数据时,
所以你的$articlenull""。 这就是它重定向到failure.php的原因。

改为使用,

$article_id = $_POST['article'];

【讨论】:

  • 查看问题下方的评论。它已经声明article 来自localhost/index.php?article=5
  • 谢谢你!您的回答让我有了自己解决方案的想法。
  • 如果此答案有助于将其标记为答案,而不是回答您自己的问题。
【解决方案2】:

对于给您带来的不便,我深表歉意,但我自己找到了解决办法。 我没有直接从 GET 获取 article_id,而是创建了一个隐藏输入字段及其值:

<input type="hidden" name="article" value="<?php echo $_GET['article'] ?>">

现在我可以使用 POST 访问这个值,效果很好:

$article_id = $_POST['article'];

我希望我可以帮助任何人!

【讨论】:

  • 如果其他人回答您的问题有帮助,请将其标记为答案,而不是回答您自己的问题。
猜你喜欢
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
  • 2013-12-03
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 2012-11-02
相关资源
最近更新 更多