I am having troubles with deleting the selected checkbox rows from mysql using php code. I tried searching for the same problem here and implementing the logic in my practice project, but it doesn't seem to work. Once I select the checkboxes to delete, it loads the blank page and nothing is deleted.
The first two parts with inserting new values and deleting the row by typing the ID work correctly.
Here's my code.
<?php
if (isset( $_POST["create"])){
$conn= mysqli_connect("localhost","root","" );
mysqli_select_db($conn, "phonebook_assignement");
$phonenumber= $_POST["number"];
$textname= $_POST["name"];
$sql = "INSERT INTO contacts(name, number) VALUES ('$textname', $phonenumber)";
//exit($sql);
$rs= mysqli_query($conn,$sql);
// exit($rs);
if ($rs) {
echo "Record inserted";
}
mysqli_close($conn);
die();
}
elseif (isset($_POST["delete"])){
$conn= mysqli_connect("localhost","root","" );
mysqli_select_db($conn, "phonebook_assignement");
$id= $_POST["id"];
$delete = "DELETE FROM contacts WHERE id=$id";
$sqlDelete= mysqli_query($conn, $delete);
enter code here
if ($sqlDelete){
echo "Record deleted";
}
mysqli_close($conn);
die();
}
elseif (isset($_POST["delete"])){
$conn= mysqli_connect("localhost","root","" );
mysqli_select_db($conn, "phonebook_assignement");
$checkbox= $_POST["checkbox"];
for($i=0;$i<count($checkbox);$i++){
$del_id = $checkbox[$i];
$deleteBox = "DELETE FROM contacts WHERE id=$del_id";
$boxDelete= mysqli_query($conn, $deleteBox);
}
if ($boxDelete){
echo "Record deleted";
}
mysqli_close($conn);
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Phonebook assignement</title>
</head>
<body>
<?php
$conn= mysqli_connect("localhost","root","" );
mysqli_select_db($conn, "phonebook_assignement");
$result= mysqli_query($conn, "SELECT * FROM contacts");
while ($rw=mysqli_fetch_row($result))
echo '<form method="POST" action="dbassignment_testcheckbox.php"><input type="checkbox" name="checkbox[]" id="checkbox" value="<?php echo $rw["id"]; ?></form>' . "ID: ". $rw[0]. "- Name: ". $rw[1]. "- Phone Number: ". $rw[2]. "<br>";
?>
<br>
<fieldset>
<form method="POST" action="dbassignment_testcheckbox.php" name="createUser">
<label for="name">Insert new name : </label>
<input type="text" name= "name" id="name">
<label for="number">Insert new phone number : </label>
<input type="text" name="number" id="number">
<input type="submit" name="create" value="Insert"><br><br>
<label for="delete">Delete row number : </label>
<input type="number" name= "id" id="delete">
<input type="submit" name="delete" value="Delete">
</form>
</fieldset>
<?php
?>
</body>
</html>
Thank you.
Aucun commentaire:
Enregistrer un commentaire