![](/img/trans.png)
[英]How to fix this error Trying to access array offset on value of type null
[英]How to fix Trying to access array offset on value of type null error
我正在使用 PHP 創建一個時間表視圖,其中我根據日期和時間獲取講座數據。
這是我所做的代碼
$monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
$result_11to1 = mysqli_query($con, $monday_lectures);
$m11to1 = mysqli_fetch_array($result_11to1);
if ($m11to1["lecture_day"] == !'') {
echo "<td>".$m11to1["lecture_name"]."</td>";
} else {
echo "<td> no class</td>";
}
但是對於上面的代碼,我遇到了以下錯誤:
警告:嘗試訪問 C:\xampp\htdocs\nexgschool\admin\notify\add_time_table.ZE1BFD762321E4099634AC0B64E84 行中 null 類型值的數組偏移量
當您在從數據庫獲取數據后收到此錯誤時,這意味着數據庫沒有找到任何匹配的行。 當沒有匹配的記錄或結果集已用盡時,大多數數據庫獲取函數返回null
或空數組。
要解決問題,您需要檢查值的真實性或您要訪問的密鑰是否存在。
$monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
$result_11to1 = mysqli_query($con, $monday_lectures);
$m11to1 = mysqli_fetch_array($result_11to1);
if ($m11to1 && $m11to1["lecture_day"] == !'') {
echo "<td>".$m11to1["lecture_name"]."</td>";
} else {
echo "<td> no class</td>";
}
如果您所追求的是結果數組中的單個值,那么您可以指定默認值以防結果不存在。
$monday_lectures = "SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'";
$result_11to1 = mysqli_query($con, $monday_lectures);
$m11to1 = mysqli_fetch_array($result_11to1);
$lecture = $m11to1["lecture_day"] ?? null;
這同樣適用於 PDO。
$monday_lectures = $pdo->prepare("SELECT * from lectures where lecture_time = '11am to 1pm' and lecture_day = 'firday'");
$monday_lectures->execute();
$m11to1 = $monday_lectures->fetch();
$lecture = $m11to1["lecture_day"] ?? null;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.