LordRaiders LordRaiders - 6 months ago 7
SQL Question

Create new page when creating post

Currently I'm making a blog out of scratch.

I already have a login page and a "create post page". But when I create a post I just store the information inside the database.

How can I make it that I create a new page for the blog post?

Something like: [sitename].com/post.php?id=1

Thanks for helping :)

Answer

Interesting question. Here I have an example on how you could do that (PDO). $_GET["id"] will take the ID from the URL. As example domain.com/post.php?id=[getid]

    <?php
        $id = $_GET["id"];
        $sql = "SELECT * FROM `posts` WHERE `id` = $id";
        $result = $conn->query($sql);
        while($row = $result->fetch(PDO::FETCH_ASSOC)) {
            echo $row["title"].' '.$row["content"];
        }
    ?>

And if you want to link them back to the homepage when the ID is not given, you could use this;

if (empty($_GET["id"])) {
        header("Location: index.php");
}

For linking from the index to the posts you can use;

        $sql = "SELECT * FROM `posts` ORDER BY `id` DESC";
        $result = $conn->query($sql);
        while($row = $result->fetch(PDO::FETCH_ASSOC)) {
             echo '<a href="posts.php?id='.$row["id"].'">';
        }

}

Comments