Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Delete Button to Delete Record from Database

I have a database containing books. On a page, I have loop that prints each record in the database which each book's title, author, publisher, date, and rating. I want to use a delete button at the bottom of each record in order to delete it.

When I click on the delete button, the page is updated, but the record is not deleted.

I have tried to find solutions to this problem, but have yet to. I tried to use the book_id category in my database table as my index, in order to identify each record and delete it but it does not work.

Here is the code for my button form, as it appears with html code:

 while ($row = mysqli_fetch_array($result)) 
 {

 echo '<div id="forminput">';

$timestamp = strtotime($row['date']);

echo '<div id = "bookpicture">';
echo '<img src="images/Book Cover 8crop.jpg" alt="Book Cover">';
echo '</div>';

echo '<div id = "bookinfo">';
echo '<div id = "titleauthor">';
echo '<h3>' . htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') . '</h3>';
echo '<p>' . htmlspecialchars($row['author'], ENT_QUOTES, 'UTF-8') . '</p>';

echo '</div>';
echo '</div>';

$id = htmlspecialchars($row['book_id'], ENT_QUOTES, 'UTF-8');

echo '</div>' ;
echo '<div id = "publisher">' ;
echo '<p>' . 'Published on' . " " . htmlspecialchars(date('F j, Y,', $timestamp),    
ENT_QUOTES, 'UTF-8') . 
" " . 'by' . " " . htmlspecialchars($row['publisher'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '<div id = "formDelete">';
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">'; 
echo '<input type="submit" value="Update" name="myAdd" id="myAdd" style = "width:  
100px" required>';
echo '<input type="submit" value="Delete" name="myDelete" id="$id" style = "width: 
100px" required>';
echo '</form>';
echo '</div>';
echo '</div>';
echo '<hr>' ;

echo '</div>';
}
?> 

Here is the code from my index.php file.

else if (isset($_POST['myDelete']))
{
$ids = mysqli_real_escape_string($link, $_POST['$id']);    

$sql="DELETE FROM readbooks WHERE book_id = '$ids'";

if (!mysqli_query($link, $sql))   

{   

$error = 'Error with submission: ' . mysqli_error($link);   

include 'php/error.html.php'; 

exit();   

  } 
}

Here is the updated code.

like image 853
Stephane Avatar asked Mar 16 '26 12:03

Stephane


1 Answers

The Problem is you are not trying to send the row ID from the form.

In Form try sending row id from the form

 echo '<input type="hidden" name="id" value="$id">'

try receiving that parameter

 $id = $_POST['id'];
 $con = mysql_connect("host address","mysql_user","mysql_pwd");
 $query = "DELETE FROM readbooks WHERE id = $id";
 mysql_query($query,$con);
like image 149
Arun G Avatar answered Mar 18 '26 01:03

Arun G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!