duanlang1196 2017-10-14 05:41
浏览 186

PHP mySQL按日期排序

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>";
    }
}
  • 写回答

4条回答 默认 最新

  • duanhuayong6687 2017-10-14 05:43
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器