簡體   English   中英

為什么在此查詢中出現未定義的索引錯誤?

[英]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 ...(對不起,我很無聊!)

您正在獲得title的未定義索引,因為數組$row沒有title

我建議你看一下你的數據庫結構表blog ,但我也建議做你的一些基本數據的檢查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>";
    }
}
?>

如果所有這些都運行且沒有任何結果,則說明您的數據庫查詢存在缺陷,因此不會返回數據。 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>";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM