0

I need the posts on my guestbook to be sorted by time ascending. I have been told that I need to add:

ORDER by datetime 

in my code. But I dont know what the correct way to enter this line is. Here is my code:

<?php

    $host = "ZZZ"; // Host name 
    $username = "ZZZ"; // Mysql username 
    $password = "ZZZ"; // Mysql password 
    $db_name = "ZZZ"; // Database name 
    $tbl_name = "ZZZ"; // Table name 

    // Create connection
    $conn = mysqli_connect($host, $username, $password, $db_name);
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

   $sql = "SELECT * FROM ". $tbl_name ." ";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            echo "
        <b>    Name: ". $row["name"]."<br>
            Date Added: : ". date('d-m-Y H:i', $row["datetime"]) ."</b><br><br>
            Comment: ". $row["comment"]."<br>
            <br> 
            ";
        }
    } else {
        echo "0 results";
    }



    mysql_close(); //close database
    ?>
Tr4p
  • 9
  • 1
  • 1
  • 5
  • 2
    `SELECT * FROM table ORDER by datetime` – u_mulder Feb 04 '16 at 08:54
  • 2
    You're mixing `mysqli` and `mysql` functions. – Daan Feb 04 '16 at 08:54
  • Also your code at http://tr4p.no/addguestbook.php is vulnerable to SQL injection. Please read http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php . And you must html-escape your output, otherwise you'll get XSS. – ksimka Feb 04 '16 at 09:00
  • This code is ***not*** vulnerable to SQL injection itself and there is no user input involved. This *coding technique* is – Hanky Panky Feb 04 '16 at 09:03
  • I will learn about XSS asap. Sorry didn't know. – Tr4p Feb 04 '16 at 09:20

1 Answers1

1
$sql = "SELECT * FROM " . $tbl_name . " ORDER BY datetime ASC";

Also you have mysql_close and your other functions are mysqli

Ben Rhys-Lewis
  • 3,118
  • 8
  • 34
  • 45