更新表中相似数据的问题

问题描述 投票:0回答:1

所以,我试图更新我的表中的数据,并在 php 中发布请求,我遇到了破坏数据库中所有表的问题。问题是:当我尝试更新表中的名称时,如果该名称之前已经存在于数据库中,则请求会更新所有相似的名称。我想知道我怎样才能避免这种情况? 这是我的代码:

<?php
//bug in edit it edits all names of the same row
include '../../database/conn.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Retrieve the user ID and updated data from the form
    $id = mysqli_real_escape_string($connection, $_POST['id']);
    $name = mysqli_real_escape_string($connection, $_POST['name']);
    $nature = mysqli_real_escape_string($connection, $_POST['nature']);
  
    // Update the user data in the database
    $query = "UPDATE alwaysusers SET name='$name', nature='$nature' WHERE id='$id'";
    if (mysqli_query($connection, $query)) {
      // Redirect to the main page if the update was successful
      header("Location: index.php");
      exit();
    } else {
      // Display an error message if the update failed
      echo "Error updating record: " . mysqli_error($connection);
    }
  } else {
    // Retrieve the user ID from the URL parameter
    $id = mysqli_real_escape_string($connection, $_GET['id']);
  
    // Retrieve the user data from the database
    $query = "SELECT id, name, nature FROM alwaysusers WHERE id='$id'";
    $result = mysqli_query($connection, $query);
  
    if (mysqli_num_rows($result) > 0) {
      // Display a form with the current user data
      $row = mysqli_fetch_assoc($result);
      $name = $row['name'];
      $nature = $row['nature'];
  
      echo "<form method='post'>";
      echo "<input type='hidden' name='id' value='$id'>";
      echo "<label for='name'>Name:</label>";
      echo "<input type='text' name='name' value='$name'>";
      echo "<label for='nature'>Nature:</label>";
      echo "<input type='text' name='nature' value='$nature'>";
      echo "<input type='submit' value='Save' class='btn btn-primary'>";
      echo "</form>";
    } else {
      // Display an error message if the user ID is invalid
      echo "Invalid user ID.";
    }
  }
  
  // Close the database connection
  mysqli_close($connection);
?>

我试过把$query里面的sql命令改成这样

    $query = "UPDATE alwaysusers SET name='$name', nature='$nature' WHERE name='$name'";
php mysql phpmyadmin
1个回答
0
投票

第一个查询似乎是正确的:

$query = "UPDATE alwaysusers SET name='$name', nature='$nature' WHERE id='$id'"

因为它只更新WHERE id='$id'

第二个做的正是你不想要的:它更新列

name
对应于输入的nameWHERE name='$name'

的所有行

我假设列

id
主键

© www.soinside.com 2019 - 2024. All rights reserved.