为什么我在这个查询中得到一个未定义的索引错误


Why am I getting an undefined index error with this query?

我正在创建一个非常简单的内容管理系统。。。不幸的是,我无法从数据库中检索帖子。我的错误是:

注意:未定义的索引:C:''wamp''www''NightOwlSoftware''index.php 中的标题

<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
    echo'<div class="blog"><h3 class="blog">' . $row['title'] . "</h3>";
    echo'<span class="blog"> Date: ' . $row['date'] . " Tag: " . $row['tag'] . "</span><hr>";
    echo'<p class="blog">' . $row['body'] . "</p>";
}
?>

这是存储数据的工作脚本,证明我的列都在那里。。。

<?php
include 'db_connect.php';
include 'functions.php';
sec_session_start();
$title = $_POST['title'];
$body = $_POST['body'];
$tag = $_POST['tag'];
$date = date_create()->format('Y-m-d H:i:s');
$sql = "INSERT INTO blog (date, title, body, tag)
VALUES ('$date', '$title', '$body', '$tag')";
mysqli_query($mysqli, $sql);
mysqli_close($mysqli);
header( 'Location: ../index.php' ) ;
?>

如果这是您得到的唯一错误(即日期、标记、正文都可以正常工作),那么您可能在创建数据库时键入了错误的内容,因此实际上没有title列。或者列可能有不同的名称,如namesubjectim_so_bored_i_dont_know_what_im_typing。。。(对不起,我很无聊!)

由于数组$row中没有title,因此您将获得title的未定义索引。

我建议您查看表blog的DB结构,但我也建议您在while中进行一些基本数据检查,以确保只呈现存在的内容。看看这个:

<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
    if (array_key_exists('title', $row) && !empty($row['title'])) {
      echo'<div class="blog"><h3 class="blog">' . $row['title'] . "</h3>";
    }
    if (array_key_exists('date', $row) && !empty($row['date'])) {
      echo '<span class="blog"> Date: ' . $row['date'];
    }
    if (array_key_exists('tag', $row) && !empty($row['tag'])) {
      echo " Tag: " . $row['tag'] . "</span><hr>";
    }
    if (array_key_exists('body', $row) && !empty($row['body'])) {
      echo'<p class="blog">' . $row['body'] . "</p>";
    }
}
?>

如果这一切都运行&没有任何呈现,那么您的DB查询有缺陷,因此不会返回数据。在while循环之前检查这一点的一个简单方法是将阵列转储到屏幕上,看看有什么:

<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
  echo '<pre>';
  print_r($row);
  echo '</pre>';
 [ rest of your code goes here]

如果可以的话,我会把它作为注释添加,因为这不是真正的答案。我同意其他人的观点,很可能DB中的列名与代码中的不匹配。

在任何情况下,当我遇到这种情况时,您都可以使用调试器或print_r。

在while循环中,添加print_r语句-

while($row = mysqli_fetch_array($result)) {
print_r($row);
echo'<div class="blog"><h3 class="blog">' . $row['title'] . "</h3>";
echo'<span class="blog"> Date: ' . $row['date'] . " Tag: " . $row['tag'] . "</span><hr>";
echo'<p class="blog">' . $row['body'] . "</p>";
}