Mauricio Andrés Mauricio Andrés - 1 year ago 68
MySQL Question

Delete row from database with a button in table (PHP)

I have this problem, I have a table which shows data form a DB, in every row of this table (which is dynamically generated) I have a button for delete the row from the DB and so the row in my table will disappear. But I have no idea of how to catch the ID or the name of the value in the DB.

Here is my php code until now:

$del = new USER();

$stmt = $find->runQuery("SELECT course_id , course_name , course_description , course_begin_date , course_price FROM courses");

$cid = strip_tags($_POST['txt_id']);

if ($del->deleteCourse($cid)) {
} catch (Exception $e) {
echo $e->getMessage();

Here is my HTML code

<table class="table">
<th>Fecha de inicio</th>

foreach($stmt->FetchAll() as $results) {
echo "<tr>";
echo '<td name="txt_id">' . $results['course_id'] . '</td>';
echo '<td>' . $results['course_name'] . '</td>';
echo '<td>' . $results['course_description'] . '</td>';
echo '<td>' . $results['course_begin_date'] . '</td>';
echo '<td>' . $results['course_price'] . '</td>';
echo '<td class="del">
<button type="submit" name="delete_course" class="btn btn-danger">Borrar</button>
echo '</form>';
echo "</tr>";


And my method of deleteCourse

public function deleteCourse($cid){

try {
$stmt = $this->conn->prepare("DELETE FROM courses WHERE course_id=:cid ");

} catch (PDOException $e) {
echo $e->getMessage();

Thanks for the help

Answer Source

you can do this by two ways if you dont want use Ajax

1.GET method

2.POST method

you can do this with GET method by passing id in url example-

echo '<a href="'.$results['course_id'].'"></a>';

then you can get this value. example-

$courseid = $_GET['uid'];

or you can do with POST method .then you need to create a form and send value in hidden field. example -

<form method="post" action="">
    <input type="hidden" name="delete_course_id" value="<?php echo $results['course_id']; ?>">
 <button type="submit" name="delete_course" class="btn btn-danger">Borrar</button>

and you will get this id after form post like

$courseid = strip_tags($_POST['delete_course_id']);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download