正在php中检索id值


Retrieving id value in php

我正在学习php,想知道是否可以获得要删除的行的id值。

例如

while ($row = mysqli_fetch_assoc($result)) {
    $id = $row['id'];
    $username = $row['username'];
    $name = $row['name'];
    echo "<tr>";
    echo "<td>$username</td>";
    echo "<td>$id</td>";
    echo "<td>$name</td>";
    echo "<td><input type='submit' class='btn btn-primary btn-sm' name='delete' value='Delete' id = $id ></td>";
    echo "</tr>";
 }

那么,我如何获取这个id值以便删除该行呢?

if(isset($_POST['delete'])){
    DeleteRow($id);
    echo "<span style='color:green'>Row deleted</span>";
}

您需要一个隐藏的输入数组来删除所有发布的ID:

echo '<input type="hidden" name="ids[]" value="'.$id.'">';

另外,不要忘记在删除查询中使用准备好的语句。

根据您的代码尝试以下操作:

while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
echo "<tr>";
echo "<td>$username</td>";
echo "<td>$id</td>";
echo "<td>$name</td>";
echo "<td>
     <form action='' method='POST'>
      <input type='hidden' name='id' value='$id'/>
      <input type='submit' class='btn btn-primary btn-sm' name='delete' value='Delete'/>
     </form>
    </td>";
echo "</tr>";
}

要删除一行,请执行以下操作:

if(isset($_POST['delete'])){
  DeleteRow($_POST['id']);
  echo "<span style='color:green'>Row deleted</span>";
}