Bouzaid
Bouzaid

Reputation: 66

delete row php&mysql dynamique link

I want to make a link to delete a record from database using dynamic links with php however i couldn't figure it out this is my code :

 <?php
$query = "SELECT * FROM posts ";
$result = mysqli_query($connect, $query);
?>

<table>
    <tr style="background: #afafaf;">
        <th>Id</th>
        <th>Title</th>
        <th>Action</th>
    </tr>
<?php
    while($rows = mysqli_fetch_assoc($result)){
        echo "<tr>";
            echo "<td class=\"center\">".$rows['id']."</td>";
            echo "<td>".$rows['title']."</td>";
            echo "<td><a href=\"delete_post.php?id=".$rows['id']."\"> delete</a></td>";
        echo "</tr>";
    }
?>
</table>

the output link would be like .../delete.php?id=X can anyone help me write the code for delete.php ?

Upvotes: 0

Views: 41

Answers (2)

Script47
Script47

Reputation: 14540

Have the below code in your page. This first checks if $_GET['id'] is set. It will only run if it is, that way you don't get Undefined Index error.

<?php
if (isset($_GET['id'])) {
    $deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);

    $delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>

I also used htmlspecialchars to sanitize the user input. You could run some validation using ctype_digit to ensure that the input is actually an integer.

I suggest using prepared statement in MySQLi to prevent SQL injection.

Edit 1

Example with ctype_digit. This checks if the id is set and if it is a number, technically you could just use ctype_digit because if id is empty then ctype will return false as var_dump(ctype_digit("")); will return false, with that logic in mind, the value must be set for ctype_digit to work and it must be an integer.

<?php
if (ctype_digit($_GET['id'])) {
    $deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);

    $delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>

Upvotes: 2

Dominique Vermeersch
Dominique Vermeersch

Reputation: 43

That would be something like this:

$deleteId = $_GET['id'];

$sql = "DELETE FROM posts WHERE id = ".$deleteId;

Remember to escape your variables before sending them off to the MySQL server.

Upvotes: 0

Related Questions