将选择的单选值插入到表的特定id中- php mysql


Insert selected radio values into a specific id of the table- php mysql

我在数据库中有一个表,当我想拒绝或接受某人的应用程序时,我只是选择单选按钮并将值发送到数据库中的表。

但是问题是该值被分配给新行,而不是分配给特定的学生id。这是我的表,你看到有添加了2个新行获得另一个id。下面是我的代码和表格:

<?php
  $status  = $_POST["status"];
  $connect = mysqli_connect("localhost","root","admin","form");
  if (!$connect) {
          die('Connect error:'. mysqli_error());
      }
      $result = mysqli_query($connect, "INSERT INTO students (status) VALUES ('$status')    ");

?>

    idstudents |fname | lname| age | nationality | status
    .....................................................
        1      |Tom   | Bern | 23  | American    | 
        2      |Lily  | Wayne| 24  | British     |
        3      |NULL  | NULL | NULL| NULL        | accepted

为了更新,您需要一个update语句,不要忘记在表单上添加一个student_id。考虑这个例子:(Same Page Process).

<?php
$students = array();
$link = new mysqli('localhost', 'username', 'password', 'database');
if(isset($_POST['submit'], $_POST['status'])) {
    $status = $_POST['status'];
    foreach($status as $student_id => $status_value) {
        $stmt = $link->prepare('UPDATE students SET status = ? WHERE idstudents = ?');
        $stmt->bind_param('ss', $status_value, $student_id);
        $stmt->execute();
    }
}
$query = mysqli_query($link, 'SELECT * FROM students');
while($row = $query->fetch_assoc()) {
    $students[] = $row;
}
?>
<form method="POST" action="">
    <?php foreach($students as $key => $value): ?>
        <fieldset>
            <p>
                Name: <?php echo $value['fname'] . " " . $value['lname']; ?><br/>
                Status: <b><?php echo ($value['status'] != '') ? $value['status'] : 'N/A'; ?></b><br/>
                <input type="radio" name="status[<?php echo $value['idstudents']; ?>]" value="accepted" /> Accepted
                <input type="radio" name="status[<?php echo $value['idstudents']; ?>]" value="rejected" /> Rejected
            </p>
        </fieldset>
    <?php endforeach; ?>
    <input type="submit" name="submit" value="Update" />
</form>

注意:因为你现在使用的是mysqli,所以要充分利用参数化查询。不要在查询中直接使用$_POST值。

INSERT语句的意思是…插入新行。您需要的是一个UPDATE语句,将一个值应用于特定的行,您将使用它们的idstudents来选择。

$status  = $_POST["status"];
$studentid  = $_POST["studentid"];
...
$result = mysqli_query($connect, "UPDATE students SET status = '$status' WHERE idstudents = $studentid;");

另外,在使用用户输入的$_POST(或其他)值时一定要小心,如果该服务将被其他人使用,您可能希望在插入之前对它们进行清理,以避免潜在的安全漏洞。