Im very new to PHP and im wondering how I can create a button to delete a post on my blog system.

My system is as follows;

Blog Page

<?php
    include ("includes/includes.php");

    $blogPosts = GetBlogPosts();

    foreach ($blogPosts as $post)
    {
        echo "<div class='post'>";
        echo "<h2>" . $post->title . "</h2>";
        echo "<p>" . $post->description . "</p>";
        echo "<span class='footer'>Date: " . $post->date . "</span>";
        echo "</div>";
    }
?>

Includes File

<?php
include 'blogpost.php';

//MySQL Connection

function GetBlogPosts($inId=null, $inTagId =null)
{
    if (!empty($inId))
    {
        $query = mysql_query("SELECT * FROM news WHERE id = " . $inId . " ORDER BY id DESC"); 
    }
    else
    {
        $query = mysql_query("SELECT * FROM news ORDER BY id DESC");
    }

    $postArray = array();
    while ($row = mysql_fetch_assoc($query))
    {
        $myPost = new BlogPost($row["id"], $row['title'], $row['description'], $row['descriptionfull'], $row["date"]);
        array_push($postArray, $myPost);
    }
    return $postArray;
}
?>

Any ideas are welcome.
Thank you

Member Avatar for diafol

Will this be a button at the bottom of the post (for admin only) or a series of delete links/buttons on a dedicated admin page?

A single button next to each post on a dedicated admin page.
Thanks

Member Avatar for diafol

I assume your admin page will be protected from unauthorized access. But still, defence in depth applies when deleting or updating the DB. I suggest using a confirmation hash in addition to passing the id of the post.

for example:

while($row = mysql_fetch_assoc($query)){
    $id = $row['post_id'];
    $hash = md5('th15 15 4 54lt' . $id . 'th15 15 an0ther 54lt');
    $button_id = $id . '_' . $hash;
    extract($row);

    echo <<<BLOG
    <h3>$title</h3>
    <p>$description</p>
    <p>$date</p>
    <button id="<?php echo $button_id;?>" class="deletebutton">Delete</button>
    BLOG;
}

Using JS/jQuery you need to capture the button id attribute from the deletebutton click event. You then pass this to an ajax function.
Pass the parameter to the php file which will strip the id and hash values via explode on "_". Check that the md5 hash is valid for the value.
If so, delete the post from the DB.
If successful echo true back to js / false if not.
This tells js whether to remove the visual post on the screen or not. You could tie in some nice animation to this if you wanted.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.