Delete each Item in a foreach PHP

461

I have a table with anforeach array of items. I want to delete each item by a link. In the DB, the table is "users" and the row is "id".

PHP code of the table:

<table >
<thead>
<tr>
<th>ID</th>
<th>USER</th>
<th>MAIL</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3">
<div ><a href="#">&laquo;</a> <a href="#">1</a> <a href="#">2</a> <a href="#">3</a> <a href="#">4</a> <a href="#">&raquo;</a></div>
</td>
</tr>
</tfoot>
<tbody>

<?php
$query = $db->query("SELECT * FROM users ORDER by id");
echo "<tr>";
while($row = $query->fetch_array()){
  $id = $row['id'];
  echo "<tr>"; //put <tr> opening code inside, not outside of while()
  echo "<td>".$row['id']."</td>";
  echo "<td>".$row['username']."</td>"; //remove <tr></tr>
  echo "<td>".$row['email']."</td>"; //remove <tr></tr>
  echo "<td><a href='delete($id)'>Delete</a></td>"; //remove <tr></tr>
  echo "</tr>"; //close tr only once at the end
}
?>
</tbody>
</table>

The function that delete the code is:

   function delete($id) {

        $sql = 'DELETE FROM users
                WHERE id = :id';

        $q = $this->pdo->prepare($sql);

        return $q->execute([':id' => $id]);
    }

I used the delete link with:

<a href='delete($id)'>Delete</a>

But didn't work. It gives the correct Id -for example (delete(5)- but didn't delete it because it shows:

The requested URL /sistema-login/admin/delete(5) was not found on this server.
427

Answer

Solution:

I don't know if you're using some sort of framework to map url parts to function parameters, but you could something like

<a href='delete/<?= $id ?>'>Delete</a>

or even

<a href='delete?id=<?= $id ?>'>Delete</a>

And then use$_REQUEST to retrieve the parameter.

At least that will send the parameter to your server. I don't know how you've mapped your functions to routes, so I don't know if you're getting the right url..

499

Answer

Solution:

I think you should use this for delete record. inwhile loop

<a href='?id=<?= $id ?>'>Delete</a>

Remove function and use$_REQUEST like below code.

if(isset($_REQUEST['id']) && !empty($_REQUEST['id']))
{
    $dbh = connectDb();
    $stmt = $dbh->prepare( "DELETE FROM users WHERE id =:id" );
    $stmt->bindParam(':id', $_REQUEST['id']);
    $stmt->execute();
}

People are also looking for solutions to the problem: php - Codeception undefined index: ELEMENT error

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.