1

I have written some code to echo my table:

<?php while($product = mysqli_fetch_assoc($result)) : ?>
    <tr>
        <td><?php echo $product['id']; ?></td>
        <td><?php echo $product['customer_id']; ?></td>
        <td><?php echo $product['total_price']; ?></td>
        <td><?php echo $product['created']; ?></td>
        <td><?php echo $product['modified']; ?></td>
        <td><a href="delete.php"><span class="glyphicon glyphicon-remove"></span></a></td>
    </tr>
<?php endwhile?>

Last td element is created for specific table row removal. However I don't know how to get that row id. This is my delete.php file:

<?php
require_once 'core/init.php';

$id = $_GET['id'];

mysqli_query($db,"DELETE FROM orders WHERE id='".$id."'");
mysqli_close($db);
header("Location: details-modal-orders.php");
?> 

I assume i should change something in this line:

<td><a href="delete.php"><span class="glyphicon glyphicon-remove"></span></a></td>

After delete.php there should be somekind of id recognizer or something. Please help. I also don't know how to create that because it is inside of a while loop. I'm afraid something is not going to work well.

2 Answers 2

2

Pass the id as a parameter via the href attribute

href="delete.php?id=<?php echo $product['id']; ?>">

Also do not forget to use prepared statements while performing this operation as it is totally unsafe to pass $_GET or $_POST or $_REQUEST parameters directly into your query

Using prepared statments

$id =  (int) $_GET['id']; //cast to integer

$stmt = mysqli_stmt_prepare($db,"DELETE FROM orders WHERE id=?"); //prepare the statement returns true/fasle
mysqli_stmt_bind_param($stmt, "i", $id); //bind placeholder to variable
mysqli_stmt_execute($stmt); //execute (returns true/false)
Sign up to request clarification or add additional context in comments.

8 Comments

Why do you use echo? Shoul'd it be just href="delete.php?id=<?php $product['id']; ?>"> ?
echo would display the id. without it the variable wouldn't be displayed
@CaL17 Then why do you <td><?php echo $product['id']; ?></td>, shouldn't it just be <td><?php $product['id']; ?></td>?
There's no need to use a prepared statement if the only data that's going in is for the GET array. Doing (int) $_GET['id'] is enough. Just a bit of a side note here ;-)
yeah.. casting to integer is okay. I just wanted to show OP how prepared statements work. lol.. thanks @Fred-ii-
|
-1

Is it serious ?

<td><a href="delete.php?id=<?php echo $product['id']; ?>">
      <span class="glyphicon glyphicon-remove"></span>
</a></td>

1 Comment

What do you mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.