How to order rows from newest to oldest MySQL & PHP? - php

I made a comments section on my website using PHP & MySQL. However all the old comments are at the top and the new comments are at the bottom. How do I flip the order so new comments are on top and old ones are at the bottom?
Here's my comments.inc.php:
<?php
function setComments($conn) {
if (isset($_POST['commentSubmit'])) {
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid', '$date', '$message')";
$result = $conn->query($sql);
}
}
function getComments($conn) {
$sql = "SELECT * FROM comments";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo "<div class='comment-box'><p>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo '<input type="button" value="More Info" onclick="window.location=\'more_info.php?start=' . urlencode($row['message']) . ' \';" />';
echo "</p></div>";
}
}
Thanks in advance! :)

Depending on the date and time we can show older once at the top and newer comments at the bottom:
SELECT * FROM comments ORDER BY date desc

SELECT * FROM comments ORDER BY date DESC

SELECT * FROM comments ORDER BY date DESC
For more info you can refer below link. All possibilities are listed.
https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html

You could use ORDER BY date DESC or same with primary key field if it is autoincrement when building your query.

Related

PHP mySQL Sort post by date

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>";
}
}
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.
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
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";
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>";
}
}

Get comments by the ID of the page

Hello i have created a databse which store the information sended by the form on my page.
The structure of the database is this :
cid(comment id) uid(value='Anonymous') id(of the page) date message(text of the message)
So when i goes to a particular page of my website, for example http://miostio.com/page.php?id=15
here i can put a comment by a form which send the information that u can see up in my database.
Now on my database are stored the id of the page in which i have putted the comments, but when i try to see the comment in that page by the function : getComments($conn); ,here are displayed all the comments saved in the database and not only the comments with the id of the page.
I want that the comments displayed corresponds to the id of the page, in page with id(15) display the comment of the page with id(15), in page with id(10) display the comment of the page with id(10) exc ...
PHP --> form that send data
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea><br>
<button name='commentSubmit' type='submit' class='comm-btn'>Comment</button>
</form>";
getComments($conn);
other PHP CODE which contain the function called by the form
function setComments($conn) {
if (isset($_POST['commentSubmit'])){
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$id = $_POST['id'];
$sql = "INSERT INTO comments (uid, date, message, id) VALUES ('$uid', '$date', '$message', '$id')";
$result = $conn->query($sql);
}
}
function getComments ($conn) {
$sql = "SELECT * FROM comments WHERE id = id ORDER BY cid DESC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<div class='comment-box'><p>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
You got at least two mistakes (I don't know yet if the rest is ok and working):
1st: Your sql statement doesn't include the variable you're aming for, it just says kinda 'if 1=1'. So change it to:
$sql = "SELECT * FROM comments WHERE id = $id ORDER BY cid DESC"
2nd: You don't have yet $id available in that function.
So include that:
function getComments ($conn) {
$id = intval($_POST['id']); // cast to int for security
$sql = "SELECT * FROM comments WHERE id = $id ORDER BY cid DESC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<div class='comment-box'><p>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
"SELECT * FROM comments WHERE id = id ORDER BY cid DESC"
id always === id
You need to give a real id there...
"SELECT * FROM comments WHERE id = $id ORDER BY cid DESC"
Would consider protecting it from sql injection like this:
"SELECT * FROM comments WHERE id = " . (int)$id . "ORDER BY cid DESC"

How to make mysql generated posts to be independent onn their own

i am retrieving posts from a table called post . I wanted to add a commenting feature to this code, The problem is that the latest posts variables are dominant over others in that if you comment on an older post, the variables of the "latest post(which appears first because of the ORDER BY ID DECS criteria"
Someone help me make this posts independent on their own...Thanks
<?php
$sqlhash="SELECT * FROM posts ORDER BY id DESC ";
$result_hash = mysqli_query($conn,$sqlhash);
while($rowhash = mysqli_fetch_assoc( $result_hash))
{
$user = $rowhash['user'];
$message = $rowhash['post'];
$time = $rowhash['time'];
$id= $rowhash['id'];
$tt = date('m/d/Y H:i:s',$time);
$my_id = $_SESSION['user_id'];
$sql="SELECT * FROM users WHERE Full_name='$user' ";
$result_set = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc( $result_set))
{
$select_username = $row['Full_name'];
$profp = $row['pic'];
$my_id = $_SESSION['user_id'];
?>
<center><div class='post' style='width:48%; height:40%; align:middle; text-align:left; margin:30px 0'>
<img width="70" height="70" src='uploads/<?php echo $profp; ?>'><br><p style='color:#0c88b5'><b> <?php echo $id ;?><br><?php echo $user ;?>On:<?php echo $tt ; ?><h4><b><?php echo $message
;?></h4></p><hr>
<?php
$sqlcom="SELECT * FROM comment WHERE hash='$id' ";
$result_com = mysqli_query($conn,$sqlcom);
while($rowcom = mysqli_fetch_assoc( $result_com))
{
$usercom = $rowcom['comment'];
$comenter = $rowcom['user'];
echo "<p style='color:#0c88b5' $comenter</p>". ":" ;
echo $usercom. "<br>" ;
}
if (isset($_POST['commen'])) {
$sqlhash= "SELECT * FROM posts WHERE post= '$message' ";
$result_hash = mysqli_query($conn,$sqlhash);
while($rowhash = mysqli_fetch_assoc( $result_hash))
{
$user1 = $_SESSION['username'];
$comment = $_POST['commen'];
$time = $rowhash['time'];
$time2 = $_SESSION['time'];
$sql3 = "INSERT INTO comment (user, comment, hash) VALUES
('$user1','$comment', '$id')";
if($conn->query($sql3) === TRUE) {
header('Location: timeline.php');
}else {
echo"error";
}
Make some changes at database level in your post table to manage the reply thread on a post.
Add a parent_id column with default null that contains the post id for which the reply or comment is made.
For each comment or reply, put an entry in parent_id column.
To show post, fetch the records having parent_id IS NULL. By this you will get the post only, put order by on id to get in a proper order.
For each post you can retrieve comment or reply by putting a condition like parent_id IS NOT NULL
This will help you.

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']);
Explicitly specify your sort key:
$data = mysql_query("SELECT * FROM ChatTest ORDER BY PostDate DESC") or die(mysql_error());

Print multiple columns individually

Using the following query:
SELECT title, nid, created FROM node WHERE uid = $account->uid ORDER BY changed DESC
How do I go about printing the title, nid, created separately (in PHP)?
Thanks! (I'm sure this is VERY simple, I'm just not used to PHP yet)
This is a very basic question, try google for tutorials. Here's a c/p from the very first google result about PHP and mysql which shows the technique you're after.
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM example")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "Name: ".$row['name'];
echo " Age: ".$row['age'];
http://www.tizag.com/mysqlTutorial/mysqlquery.php
If you expect only one result:
$query = "SELECT title, nid, created FROM node WHERE uid = '".$account->uid."' ORDER BY changed DESC";
$resource = mysql_query($query) or die (mysql_error());
if(mysql_num_rows($resource)>0)
{
$row = mysql_fetch_array($resource);
echo 'Title: '.$row['title'].'<br />';
echo 'ID: '.$row['nid'].'<br />';
}
else
{
echo 'no record found';
}
Otherwise (i reread the title of the question now, sorry)
while ($row = mysql_fetch_array($resource))
{
echo 'Title: '.$row['title'].'<br />';
echo 'ID: '.$row['nid'].'<br />';
}

Categories