简体   繁体   中英

Load MySql table from bottom to top - PHP

Today is my first day ever messing with PHP or MySQL... I tried to make a simple chat program... it works great but it displays the old chats first and the newest chats (which are at the bottom of my table) last (at the bottom of the page).. how can I load the table in reverse order? So it displays the rows front he bottom of the database table at the top of my HTML table?

Here is my code... All in the file called "Chat.php"

<html><head></head><body>
<form action="chat.php" method="post">
Message: <br><textarea type="text" name="message" style="width:80%; height:300px;"></textarea><br>
<input type="submit" />
</form>

<?php

$host="****";
$user="****";
$password="****";

$cxn = mysql_pconnect ($host, $user, $password);

mysql_select_db("defaultdb", $cxn);

if (getenv(HTTP_X_FORWARDED_FOR)) {
    $ipaddress = getenv(HTTP_X_FORWARDED_FOR);
} else {
    $ipaddress = getenv(REMOTE_ADDR);
}

$message = $_POST["message"];

mysql_query("INSERT INTO ChatTest (ID, TimeStamp, Message) VALUES ('$ipaddress', NOW(), '$message')");

$data = mysql_query("SELECT * FROM ChatTest") or die(mysql_error()); 
 Print "<table border cellpadding=3>"; 
 Print "<tr>"; 
 Print "<th>ID:</th><th>TimeStamp:</th><th>Message:</th>";
 while($info = mysql_fetch_array( $data )) { 
 Print "<tr>"; 
    Print " <td>".$info['ID'] . "</td> "; 
    Print " <td>".$info['TimeStamp'] . " </td>";
    Print " <td>".$info['Message'] . "</td></tr>"; 
 } 
 Print "</table>"; 

mysql_close($cxn);


?>
</body></html>

What you are looking for is MySQL's ORDER BY statement. You can use it to tell the DBMS in which order you want your results.

SELECT * FROM ChatTest
ORDER BY `TimeStamp` DESC

And just another thing…

I realize that this is your first attempt, so it's understandable that there'll be mistakes. One thing, however, you should learn about right away is SQL Injections .

Consider an example where the user's message is

0'); DROP TABLE ChatTest --

So suddenly your query would look like

INSERT INTO ChatTest (ID, TimeStamp, Message)
VALUES ('$ipaddress', NOW(), '0'); DROP TABLE ChatTest --')

To prevent this, always run user input through mysql_real_escape_string() , like this:

$message = mysql_real_escape_string($_POST['message']);

明确指定您的排序键:

$data = mysql_query("SELECT * FROM ChatTest ORDER BY PostDate DESC") or die(mysql_error()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM