在表PHP的末尾添加一个删除按钮

时间:2014-07-25 15:08:45

标签: php mysqli sql-delete

我已将MySQL表的结果输出到HTML表。在最后一列中,我想添加一个删除用户的删除选项。我似乎无法让它继续工作,尽管它只是在调用最后一行。

<?php

require("connection.php");

$sql="SELECT * FROM userdetail inner join usertype on userdetail.userType = usertype.userID";
$query = mysqli_query($con,$sql);

$list = '';
while($row = mysqli_fetch_assoc($query)){
    $userID = $row['userID'];
    $userName = $row['userName'];
    $email = $row['email'];
    $usertype = $row['userType'];
    $address = $row['address'];
    $postalCode = $row['postalCode'];

    $list .= "<tr><td>".$userID."</td><td>".$userName."</td><td>".$usertype."</td><td>". $email."</td><td>". $address."</td><td>".$postalCode."</td><td><form method='post'> <input type='submit' name='remove' value='Remove'> </form></td></tr>";
}

if(isset($_POST['remove'])){
    $sql = "DELETE * FROM userdetails WHERE userID = $userID ";
    $query = mysqli_query($con,$sql);
    if (mysql_affected_rows() == 1) { 
        echo 'Contact Has Been Deleted';
    } else { 
        echo 'Deletion Failed';
    } 
}

?>


<html>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>User Type</th>
<th>Email</th>
<th>Address</th>
<th>Postal Code</th>
</tr>
<?php echo $list;?>
</table>
</html>

1 个答案:

答案 0 :(得分:2)

$userID不在移除主体的范围内,在while循环之前初始化

<?php

require("connection.php");

$sql="SELECT * FROM userdetail inner join usertype on userdetail.userType =     usertype.userID";
$query = mysqli_query($con,$sql); 
$userID = '';
$list = '';
while($row = mysqli_fetch_assoc($query)){
$userID = $row['userID'];
$userName = $row['userName'];
$email = $row['email'];
$usertype = $row['userType'];
$address = $row['address'];
$postalCode = $row['postalCode'];

$list .= "<tr><td>".$userID."</td><td>".$userName."</td><td>".$usertype."</td><td>". $email."</td><td>". $address."</td><td>".$postalCode."</td><td><form method='post'> <input type='submit' name='remove' value='". $userID ."'> </form></td></tr>";
}

if(isset($_POST['remove'])){
echo $sql = "DELETE FROM userdetails WHERE userID = '".$_POST['remove']."' ";
$query = $con->query($sql);
if ($query == 1) { 
    echo 'Contact Has Been Deleted';
} else { 
    echo 'Deletion Failed';
} 
}

?>