Emm Emm - 1 year ago 53
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">
<!-- Comienza PHP -->

$i = 0;
foreach ($resultados as $fila) {

<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'";

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

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

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

echo "Hubo un error en la selección";

} ?></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>


<?php } ?>

The 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();
// ----------- TERMINA CONEXIÓN -----------------

$id = $_POST['id'];

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


$conexion = null;


Answer Source

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

     //get the id into php variable like below
     $id = $_GET['id'];

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


Hope this work!!!