我正在尝试做一个程序,当一个项目与相同的描述,标题,颜色等创建它将改变旧的价格。
但是,当我在SQL表中创建一个新行时,会出现以下错误
Notice: Trying to access array offset on value of type null in C:\xampp\htdocs\Projects\dad\PHP\addproduct.php on line 18
下面是我到目前为止制作的代码。
<?php
require("./sql.info.php");
$title = stripcslashes(mysqli_real_escape_string($con, $_POST["Title"]));
$col = stripcslashes(mysqli_real_escape_string($con, $_POST["ColourMat"]));
$desc = stripcslashes(mysqli_real_escape_string($con, $_POST["Description"]));
$price = stripcslashes(mysqli_real_escape_string($con, $_POST["Price"]));
$title_low = strtolower($title);
$col_low = strtolower($col);
$desc_low = strtolower($desc);
if (isset($_POST["Submit"])) {
if (isset($title) && isset($title_low) && isset($col) && isset($col_low) && isset($desc) && isset($desc_low) && isset($price)) {
$res = mysqli_query($con, "SELECT * FROM products WHERE lower(Title) = '$title_low' AND lower(ColourMaterial) = '$col_low' AND lower(ItemDescription) = '$desc_low'") or die(mysqli_error($con));
$row = mysqli_fetch_array($res);
if (strtolower($row[1]) == $title_low && strtolower($row[2]) == $col_low && strtolower($row[3]) == $desc_low) {
$query = mysqli_query($con, "REPLACE INTO products VALUES ('$row[0]', '$title', '$col', '$desc', '$price')");
header("Location: ../a/test.html");
} else {
$query = mysqli_query($con, "INSERT INTO products (Title, ColourMaterial, ItemDescription, Price) VALUES ('$title', '$col', '$desc', '$price')");
}
}
}
?>
第18行:
if (strtolower($row[1]) ...
当没有匹配项时抛出错误。 你会想要检查是否有结果,例如做:
if( mysqli_num_rows($res) ) { // will execute only if rows were returned
$row = mysqli_fetch_array($res);
或者:
if ($row = mysqli_fetch_array($res)) { // will not execute if NULL is returned
...
或者:
if (is_array($row) && strtolower($row[1]) ... // will not execute if $row isn't an array
要点是,如果没有结果,$row
将为NULL,并且NULL[1]
将像上面一样向您尖叫。
始终对代码的条件执行进行必要的检查,确保只有在必要的资产(如array$row
)可用的情况下才执行特定的代码部分。