Edva Ptr Edva Ptr - 1 year ago 63
PHP Question

Delete wrong record from table

I need your advice. I fetch data from database to table: ID, Name.
In table are Actions: Delete, Enable, Block. When action Delete
is selected, I would like, that respectively record will be deleted.
However, my script does not work and always delete last record, even I select
another record. I think problem is, that select name and hidden input
name is similar for all records. But I can not find way, how to create
them with different names.
Any advice is welcome.


<form method='post'>
<table border='1'>
<th> ID </th>
<th> Name </th>
<th> Action </th>


$db = new PDO('mysql:host=localhost;dbname=****;charset=utf8', '**', '**');
$query = $db->query("SELECT ID,statusas,login,vardas,email FROM users");

while($row = $query->fetch(PDO::FETCH_BOTH)) {
echo "<tr><input type='hidden' name='id' value='".$row[0]."'>";
echo "<td>".$row[0]."</td>";
//echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
//echo "<td>".$row[3]."</td>";
// echo "<td>".$row[4]."</td>";
echo "<td><select name='action'>
<option value='choose'>Choose..</option>
<option value='delete'> Delete </option>
<option value='enable'> Enable </option>
<option value='block'> Block</option>
echo "</tr>";
echo "<br><input type='submit' name='submit'></table></form>";

if($_POST['submit']) {
if ($_POST['action']== 'delete') {
echo $_POST['id']; // delete query, but now I am just checking if I get a proper ID.
else {
echo "bad";


Answer Source

You are using the same name attribute on every row in the form, so they are being overridden and it's using the last one.

What you could do is either wrap every row in its own form, or you could do something like this, and have only 1 submit button to execute the action on every row:

// remove hidden id element


echo "<td><select name='action[" . $row[0] . "]'>"

// remove submit button in the loop, but add it after the while loop

if (isset($_POST['action']))
    foreach ($_POST['action'] as $id => $action)
        if ($action !== 'choose')
            // do action on the id;
            echo $id . " -> " . $action . "<br>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download