简体   繁体   中英

How to remove posts in a PHP blog

I am making a online market style website and right now users are allowed to post their sales on it, but I want the admin role to be able to edit/delete posts. What I was thinking is like a small button in the corner of each "post". The thing is I don't know how to do it so each button is unique, maybe connect them by ID or something?

<?php
    include("../dbaccess.php");
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "SELECT * FROM market";
    $result = $conn->query($sql);
    if ($result->num_rows > 0 ) {
        while($row = $result->fetch_assoc()){
            print("<div class='marketProducts'><h1 class='marketh1'>"
            . $row['id'] .$row['product'] . " - " . $row['price'] . "€</h1>"
            . "<p class='marketDescription'>" . $row['description'] 
            . "<p class='marketSeller'>" . $row['seller'] . "</p></div>");
        }
    }
    else{
        print("No active sales.");
    }
    $conn->close();
?>

Create a file named {YOUR_OWN_DIRECTORY}/delete.php and in this file write the logic to delete the post using id of the blog like this:

$id = $_GET['post_id'];
$query = $db->prepare('DELETE FROM table_name WHERE id = ?');
$query->bind_param('i', $id);
$query->execute();
/* And other code that you want */

And in the blogs view, you will be having a php forloop to show all the blogs. You can add a button anywhere with a link to the delete file with the id that you'll get by echoing like this

<?php foreach($blogs as $blog): ?>
/* Rest of your view code will be here, I am just writing the delete button code *.

<a href="{YOUR_OWN_DIRECTORY}/delete.php?post_id=<?php echo $blog['id']; ?>">

<button type="button">Delte</button>

</a>

<?php endforeach; ?>

And when the user clicks the button it will run the code form delete.php file.

I hope I got the question right and it helps!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM