使用PHP从SQL中删除用户数据



嗨,当用户在我的bookingbeforedependent.php文件中单击"删除"时,我正试图删除用户的预订详细信息,但由于某种原因,当我测试我的php文件时,一旦我单击删除,它就会转到我的delete.php屏幕,并表示它无法从数据库中删除,并出现错误Undefined index:rn。我的rn没有定义吗?对不起,我是新手。下面是我的代码:

bookingbeforedependent.php:

<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
<body>
<?php
include "config.php"; 
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);

if (!$DBC) {
echo "Error: Unable to connect to MySQL.n". 
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit; 
};

echo "<pre>";  
$query = 'SELECT roomname, checkindate, checkoutdate FROM booking';
$result = mysqli_query($DBC,$query);

if (mysqli_num_rows($result) > 0) {

echo "Delete Bookings" ?><p><?php 
while ($row = mysqli_fetch_assoc($result)) {
echo "Room name: ".$row['roomname'] . PHP_EOL;
echo "Check in date: ".$row['checkindate'] . PHP_EOL;
echo "Check out date: ".$row['checkoutdate'] . PHP_EOL;
?>
<a href= 'delete.php?rn=$result[roomname]'>Delete</a> <a href="index.php">[Cancel]</a>

<?php
echo "<hr />";
}
mysqli_free_result($result);
}
echo "</pre>";

echo "Connectted via ".mysqli_get_host_info($DBC); 
mysqli_close($DBC);
?>

</body>
</html>

delete.php:

<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
body>
<?php
include "config.php"; 
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);

if (!$DBC) {
echo "Error: Unable to connect to MySQL.n". 
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit; 
};

echo "<pre>";  
$roomname=$_GET['rn'];
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname = 
'$roomname'";
$result = mysqli_query($DBC,$query);
if($result)
{
echo "<font color='green'> Booking deleted from database";
}
else {
echo "<font color='red'> Failed to delete booking from database";
}
?>

我认为这将有所帮助:

  1. 如上所述,您需要从PHP打印
<a href= 'delete.php?rn=$result[roomname]'>
// To 
<a href= 'delete.php?rn=<?= $row['roomname'] ?>'>
// Explanation:
// 1. <?= ... ?> is the short form of <?php echo ... ?>
// 2. The `roomname` came from $row, not $result ($result is the MySQLi Object)
// 3. You need to quote the `roomname` because without it `roomname` will be readed
//    as Constant, and may Throw a Warning message
//
  1. 您的DELETE不正确,正确的是DELETE FROM ... WHERE ...
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname = 
'$roomname'";
// To
$query = "DELETE FROM booking WHERE roomname = '$roomname'";

额外:3.您可以为$roomname 指定一个默认值

$roomname=$_GET['rn'];
// To
$roomname=$_GET['rn'] ?? 'default if null';
// if the rn index doesnt exist, the $roomname value will be `default if null` instead of throwing a Warning
  1. 尝试使用Prepared-StatementSQL而不是编写它。(我不知道这个例子,但它可以防止SQL注入(

相关内容

  • 没有找到相关文章

最新更新