Emm Emm - 2 months ago 9
HTML Question

How to delete row of table with a button inside

Hi, good afternoon. I have a table generated with The foreach construct, on each '<'tr> there is a delete button inside. I want to delete the row containing the button (by the ID) but all I've done is delete the last row (the last ID) that was saved and not the desired. Thank you for your time and attention!!

This is a part of my code HTML :

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<table class="Pizarra" id="pizarra" cellspacing="0px";>
<tr class="trThDos">
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tbody>
<!-- Comienza PHP -->
<?php

$i = 0;
foreach ($resultados as $fila) {
?>
<tr>

<input type="hidden" name="id" value="<?php echo $fila['ID']; ?>" />
<td class="tdTurno"><?php echo '#' . ++$i ?></td>
<td class="tdImg"><?php echo $fila ['value'];

switch ($fila['value']){

case "0":
echo "<img src='./img/consulta-56-2.png'";
break;

case "1":
echo "<img src='./img/shot-56-2.png'";
break;

case "2":
echo "<img src='./img/ta-56-2.png'";
break;

case "3":
echo "<img src='./img/cert-56-2.png'";
break;

default:
echo "Hubo un error en la selección";
break;

} ?></td>
<td><?php echo $fila ['nombre']; ?></td>
<td class="tdHr"><?php echo $fila ['hora']; ?></td>
<td><input type="submit" class="btnBorrar" name="btnBorrar" value="X"></td>

</tr>

<?php } ?>
</tbody>
</table>
</form>


The PHP:

<?php
// ----------- CONEXIÓN ------------------
try {
$conexion = new PDO('mysql:host=localhost;dbname=farmacia', 'Emm', ' ');
$conexion->exec("set names utf8");
//echo "Conexión OK <br />";

}catch(PDOException $e){
echo "Error: " . $e->getMessage();
die();
}
// ----------- TERMINA CONEXIÓN -----------------

if(isset($_POST['btnBorrar'])){
$id = $_POST['id'];

$statement = $conexion->prepare("DELETE FROM eventos WHERE ID = $id");
$statement->execute();
//fetchAll' es clave para que invoque (llame) TODOS los elementos
$resultados = $statement->fetchAll();

header("Location:index.php");

$conexion = null;
}

?>

Answer

Use GET method instead of POST

In your HTML instead of using submit button use link as shown in below

<a href="your\php\file\path\delete.php?id=<?php echo $fila['ID']; ?>">X</a>

In the delete.php do like following

<?php 
   if(isset($_GET['id'])){
     //get the id into php variable like below
     $id = $_GET['id'];

     //sql query to delete with id variable in where clause

   }
?>

Hope this work!!!

Comments