需要保留表上数据的空白字段


Need to keep blank field with the data on the table

所以我试图让用户更新这个表,但如果字段留空,我希望数据不被保留,而不是将其更改为空白字段或 null,有什么想法吗?

<?
    elseif ($Code == "U")
    {
    $sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
    $result= mysqli_query($link,$sql) or die(mysqli_error($link));
    $showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
    while ($row = mysqli_fetch_array($showresult))
       {
        echo ("<br> ID = ". $row["IDNO"] . "<br> NAME =  " . $row["Name"] . "<br>");
        echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
        echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
       }
    }
    ?>
$fields = array(); // Take a blank array of fields and values.
$Name = trim($Name); // Trim the variable, user may add only spaces
$Genre = trim($Genre); // Do this for all variables.
$Starring = trim($Starring);
$Year = trim($Year);
$BoxOffice = trim($BoxOffice);
if (! empty($Name)) { // If user has filled the field, append to array.
$fields[] = "Name = '$Name'";
}
if (! empty($Genre)) {
$fields[] = "Name = '$Genre'";
}
if (! empty($Starring)) {
$fields[] = "Name = '$Starring'";
}
if (! empty($Year)) {
$fields[] = "Name = '$Year'";
}
if (! empty($BoxOffice)) {
$fields[] = "Name = '$BoxOffice'";
}
if (! empty($fields)) { // If the array is not empty, go for Query.
$sql = "UPDATE movieDATA SET "; // If user has not added any field value,
$sql .= implode(', ', $fields); // no SQL Query will be fired.
$sql .= " WHERE IDNO = '$idno'";
}

您的要求:

不更新用户留空的字段。

溶液:

  • 添加 if 条件以检查每个字段是否已填充。

一种方法可以做到这一点:

$q_set = [];
if (!empty($Name)) {
  $q_set []= "Name = '$Name'";
}
if (!empty($Genre)) {
  $q_set []= "Genre = '$Genre'";
}
/* ... */
if (!empty($q_set)) {
  $sql = "UPDATE movieDATA SET " . implode(',', $q_set)
    . " WHERE IDNO = '$idno'";
}

请注意,传递给 SQL 的变量应该被转义