0

I'm trying to create a website where anyone can post anything to it without creating an account, long as its just text. My problem is because every time I start the website and post something. Its sent to the bottom, where oldest posts are at the top and new posts are sent to the top. I want to see the new posts on top instead. This is my first time working with PHP, mySQL and databases in general so my code might look bad. Tell me if more information / code is needed. Thank you for your time.

<?php
function setPosts($conn){
    if(isset($_POST['postSubmit'])){
        $pid = $_POST['pid'];
        $date = $_POST['date'];
        $message = $_POST['message'];

        $sql= "INSERT INTO post(pid, date ,message) VALUES ('$pid', '$date', '$message');";
        $result = mysqli_query($conn, $sql);
    }
}

function getPosts($conn){
    $sql = "SELECT * FROM post";
    $result = mysqli_query($conn, $sql);
    while($row = $result->fetch_assoc()){
        echo "<div class='post-box'>";
        echo $row['date']."<br>";
        echo nl2br($row['message'])."<br><br>";
        echo "</div>";
    }
}
1
  • Type "mysql sort" into Google, and you got the answer ... Commented Oct 14, 2017 at 5:43

4 Answers 4

2

You need to add "ORDER BY" to your "SELECT" to sort it.

$sql = "SELECT * FROM post ORDER BY date DESC";

The "DESC" is there so that new posts will be on top. We'd use "ASC" if we wanted older posts on top.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to use ODRER BY clause like below :-

$sql = "SELECT * FROM post ORDER BY date DESC";

Reference:- ODRER BY clause

Note:- Your insersion code is wide open for SQL Injection. Use mysqli prepared statements to prevent from it.

Reference:- mysqli::prepare

3 Comments

Wow that makes me feel really stupid. But thank you for taking the time to read this and answer my question.
@SpaceOctopus or you can order the array in php, or, my preferred method, handle the display order with a bit of JavaScript.
@SpaceOctopus glad to help you :):). Please take care of note section too
1

You need to sort mysql result by date and order it in descending order.replace mysql query to this

$sql = "SELECT * FROM post SORT BY date order BY DESC";

Comments

0
function getPosts($conn){
    $sql = "SELECT date,message FROM post ORDER BY date DESC";
    $result = mysqli_query($conn, $sql);
    while($row = $result->fetch_assoc()){
        echo "<div class='post-box'>";
        echo $row['date']."<br>";
        echo nl2br($row['message'])."<br><br>";
        echo "</div>";
    }
}

Comments

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.