PHP mySQL Sort post by date - php

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

Related

how can I select and display all the rows from the same user, underneath each other with php

Users can add their workouts into a database. There will have more than one workout per user. How can i display the workout names for the logged in user, underneath each other? I have no problem adding the workouts. When I echo the names of the added workouts, it display right next to each other like "workout1workout2". I want to be able to display the workouts underneath each other. I have no idea how to do it. It would be best if I could display each workout as a button.
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' ";
$results = mysqli_query($db, $query);
while($data = mysqli_fetch_array($results)) {
echo $data['workout'];
}
Firstly, you shouldn't put that username in query like that. Look into SQL Injection and how to avoid that in PHP.
As for displaying buttons/workouts. You can embed HTML code inside the echo statement like below. You can add any html like that and it will render HTML.
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' ";
$results = mysqli_query($db, $query);
while($data = mysqli_fetch_array($results)) {
echo "<button>$data['workout']</button></br>";
}
$query = "SELECT * FROM info WHERE username='$_SESSION[username]' Group By username";

How to order rows from newest to oldest MySQL & 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.

How Sort data from database in php when using while in php

I want to sort date, time from the database from new to old ( high to low ) and I use this code but didn't work!
can you help me?
and I want MySqli Solution and it uses while because I don't know how many numbers of information I will receive from the database!
$sql = "SELECT * FROM orders WHERE seller='$id' ORDER BY dtime ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ordernumber = $row['ordernumber'];
echo "<ul> <li> $ordernumber</li></ul>";
}
}
If you want to get more details for ordering then click Here.
In your code, you should write like this below,
$sql = "SELECT * FROM orders WHERE seller='$id' ORDER BY dtime DESC";
And please do some search for ordering for your doubt.
Thanks..!!

Show Newer Data first in mysqli

How would I go about displaying data from new to old? Right now it shows the oldest posts on top and each new post is placed underneath it.
<?php
require_once('connectimage.php');
$sql ="SELECT * FROM table WHERE id=1";
$res = mysqli_query($conn,$sql);
if(mysqli_num_rows($res) > 0){
while($row = mysqli_fetch_assoc($res)){
echo " ".$row['data']." ";
//newest post
//oldest post
}
}
else{
echo "fail";
}
mysqli_close($conn);
?>
Posting this as a community wiki; I've nothing to gain from this.
Read the manual on how to "order by", it's MySQL 101 stuff.
http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
It's all in there.
See also http://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html
Btw, community wikis have no rep gain.
As you said:- How would I go about displaying data from new to old?
So you need to go for ORDER BY clause with sort order DESC like below:-
$sql ="SELECT * FROM table ORDER BY id DESC";
Note:-
I removed WHERE id = 1 part because it will give you only one record not all records.Thanks

Why does this only display one of my records?

I am trying to get pagination working on my website. Everything should be working but this only displays one product, however that should be 8 products. Anybody know what's wrong?
Thanks in advance.
else {
$query = "SELECT COUNT(*) FROM products";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9;
$pages->paginate();
$query = "SELECT serial, name, description, price, picture FROM products WHERE serial != '' ORDER BY serial ASC $pages->limit";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
{
echo '<div style="margin-bottom:10px;display:inline-block;background-color:#E3E3E3;width:190px;height:200px;"><img style="padding-top:10px;padding-left:25px;width:150px;height:150px;" src="'.htmlspecialchars($row[4]).'"><br><div align="center"><b>'.htmlspecialchars($row[1]).'</b><br><h6>€'.htmlspecialchars($row[3]).'</h6></div></div>';
};
echo ' ';
echo '<br><br><div style="margin-left:330px;">';
echo $pages->display_pages();
echo '</div>';
}
?>
mysql_fetch_row() only fetches one row at a time. You need to call it repeatedly to display all rows, like this:
while ($row = mysql_fetch_row($result)) {
// handle single row
}
I suggest you consider using mysql_fetch_array() instead. Then you will not have to rely on the order of the columns anymore and your code becomes more legible:
$row[0] becomes $row["serial"] etc.
Try reading the articles that #Kush linked. See here for a PHP-specific discussion.
You do not seem to be using mysql_fetch_row() properly
The following code is vulnerable to SQL injection because $page->limit does not appear to be sanitized
$query = "SELECT serial, name, description, price, picture FROM products WHERE serial != '' ORDER BY serial ASC $pages->limit";
Stop using mysql_* functions as they're deprecated. Use PHP database objects (PDO) instead because PDO allows parameter binding which protects you from sql injection.
You can read up on using PDO here
because of this line
$row = mysql_fetch_row($result);
should be
while($row = mysql_fetch_row($result)){...
Change the line
$row = mysql_fetch_row($result);
to
while ($row = mysql_fetch_row($result))

Categories