Show Newer Data first in mysqli - php

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

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

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..!!

Pagination count returning no value

Was hoping someone could give me some help. I have been trying to learn pagination but have run into an issue. when I run this to get my total rows count:
$sql = "SELECT COUNT (*) FROM item WHERE fid='17'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
$rows comes back with no value, I am under the impression that $rows should contain the total number of records from item with the fid of 17, when I run SELECT COUNT (*) FROM item WHERE fid='17' in phpmyadmin it returns 98 which is the correct count. Directly before the above code I use this code to connect to the db, which I use again later to display the records which works fine.
$con=mysqli_connect("$host","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
This statement displays records later in the script
$sql = mysqli_query($con,"SELECT * FROM item WHERE fid='17' ORDER BY id DESC $limit ");
So there is data and the info is correct.
I have been following this tutorial on the subject http://www.developphp.com/view.php?tid=1349 and it works like a charm on his example in the video, all I have changed is the database particulars to mine. Can't figure this one out, been stuck for days so now I am bothering you fine folks.
Update: Changed
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$rows = $row[0];
to
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rows=mysqli_num_rows($result);
// Free result set
mysqli_free_result($result);
}
And everything is working now. Still wish I knew what was wrong with my original code but I will be moving on. Thanks Phil Perry for all your help this morning!
Well, you could SELECT * FROM... and then call mysqli_num_rows($query). Probably slower than SELECT count(*). BTW, I presume that item is not a reserved word in SQL. You can always wrap table and field names in backticks (not quotes ' or "). You could also try SELECT count(*) AS myCount....
try this,
$sql = "SELECT COUNT(*) FROM item WHERE fid='17'";
$query = mysqli_query($sql);
$row = mysqli_fetch_array($query);
$rows = $row[0];

PHP Script Not erroring and not running

My code is this:
<?php
echo "Test1";
$con=mysqli_connect("Removed");
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
var_dump($GetType);
var_dump($Amount);
$sql_query = "SELECT * FROM EventRecord WHERE EventType='$GetType' ORDER BY EventId DESC";
$sql_result = mysqli_query($con,$sql_query)
or exit(mysqli_error($con));
while($sql_row = mysqli_fetch_assoc($sql_result)){
echo $sql_row['EventId'].'<br>';
}
mysqli_close($con);
?>
For some reason, when I go to http://www.example.com/MyPhp.php?Type=Join&Amount=10, all that is outputted is "Test1string(4) string(2)".
Note: I am aware of SQL Injection vulnerabilities, however they do not affect me specifically with this code. All table structure is correct.
Additionally, how would I make it echo the top rows, as determined by how large the EventId is, but echo only the top 2, or top 3, or top 7, or top any other number, depending on what $Amount is?
Replace
$sql_result = mysqli_query($con,$sql_query)
or exit(mysqli_error($con));
With
if(!($sql_result = mysqli_query($con,$sql_query))) {
exit(mysqli_error($con));
}
See :
PHP: mysqli::$error - Manual
and PHP: mysqli::query - Manual
How about using the LIMIT to display the first $Amount results from the database?
SELECT * FROM EventRecord WHERE EventType='$GetType' ORDER BY EventId DESC LIMIT 0, $Amount
Please correct me if I your question.

PHP: How to increment a value in the table row to count views and to limit counts to one IP address

I'm using the following to inset a number into 'mviews' every time some map is viewed.
Question 1. Where in the following code do i add 'ON DUPLICATE KEY UPDATE mviews = mviews+ 1' so it can increment on duplicate?
Question 2. How do i limit counts to one IP?
Question 3. How can i limit this IP to only increment the 'mviews' only within 24 hours; only the first view will be counted on every 24 hours, the rest of the views within 24 hours after the first view are not suppose to be counted.
<?php
require_once 'db_conx.php';
$result = mysql_query( "UPDATE profiles SET mviews = '1' WHERE pid = '2' ") or die (mysql_error());
/*ON DUPLICATE KEY UPDATE mviews = mviews+ 1 */
if($result){
echo "Views + 1";
}
else {
echo "Views inser error";
}
mysql_close($con);
?>
DUPLICATE KEY UPDATE
is used with INSERT and not with UPDATE statement DOCS
count for one IP will be like this
SELECT COUNT(*) FROM profiles WHERE IP = "127.1.0.0";
[If you are not looking for what I have written above]
if IP address is your primary key then
INSERT INTO
profiles (ip,views)
VALUES ("127.1.0.0",1)
ON DUPLICATE KEY
UPDATE views=views+1;
If you want your Code to work properly[dont use mysql_* also escape user input]
<?php
require_once 'db_conx.php';
$result = mysql_query( "SELECT * FROM profiles WHERE pid =2") or die (mysql_error());
/*ON DUPLICATE KEY UPDATE mviews = mviews+ 1 */
if(mysql_num_rows($result) == 0){
mysql_query( "INSERT INTO profiles (views) value(1) ") or die (mysql_error());
}else {
mysql_query( "UPDATE profiles SET mviews = mviews +1 WHERE pid = '2' ") or die (mysql_error());
}
mysql_close($con);
?>
To both Eustatia & Arun Killu - THANK YOU!!! Because of your posted/edited solution, I was helped out of a mind-bending jam. I have to create an addendum (as my currently-resolved situation may be of help to someone reading this).
My situation was how to establish a click-tracking process for a variable-based hyperlink (i.e.);
<a target="_blank" href="<?php echo $link;?>"><b><?php echo $title;?></b></a>
I kept getting the link to echo out the representative information, open the correct, id-tagged link request (and not baffle user expectation of conventional click-behavior), but the ability to MULTIPLY log link clicks was solved by this post. NOTE TO THE SUPRA-FINICKY - YES! PDO IS THE DEFACTO STANDARD.
I apologize PROFUSELY for spreading the rank taint of deprecation, but if I understand what I'm doing now, I should be able to assimilate rudimentary PDO mastery in a 3 - 6 week period.
<?php
/** Connect to DB */
mysql_connect("localhost","database_user","pwd") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$id = mysql_real_escape_string($_GET['id']);
/** retrieve URL */
$result = mysql_query("SELECT * FROM `articles` WHERE ID = '$id'") or die(mysql_error());
/*ON DUPLICATE KEY UPDATE clicks = clicks+ 1 */
if(mysql_num_rows($result) == 0){
mysql_query("INSERT INTO `articles`(`clicks`) value(1)") or die (mysql_error());
}else {
mysql_query("UPDATE `articles` SET clicks=clicks+1 WHERE `id` = '$id'") or die (mysql_error());
}
$row = mysql_fetch_array($result);
mysql_close();
header("Location: " . $row['link']);
?>
I ended up changing the configuration of the link so the id passed the correct link to the target page;
<?php echo "<a href='pagetracking.php?id=" . $id . $link . "' target='_blank'>
<font color='#0000CC' size='5'><b>" . $row['title']. "</b></font></a>"; ?>
Thank you SO MUCH for posting Eustatia & Arun Killu, I really appreciate the tip. If anyone else here happening across this sees anything that's EXCEPTIONALLY unforgivable (even in this decrepit state, lol) - PLEASE, do - not - hesitate - to scream on it robustly. I need all the help I can get.
As promised for anyone who'd be in need of a WORKING version of this in PDO;
(this is adapted from an answer that I found here on SO, but, can't remember at the second, so I'll look it up for an edit to give the answerer credit.)
track.php
<?php
//Your database information
include '../includes/db.php';
// Fetch id (article_id) from $_GET parameter
$article_id = '';
if (isset($_GET['id'])) $article_id = intval($_GET['id']);
if (!$article_id) {
print "No article ID found!\n";
} else {
//
// Fetch Article ID
//
$sql = "SELECT * FROM `articles` WHERE article_id = :article_id";
$sth = $pdo->prepare($sql);
$sth->bindParam(":article_id", $article_id);
$sth->execute();
}
if (!$sth) {
// No article!
echo 'Invalid Article ID!\n';
} else {
// Article found!
//
// Update Clicks Column
//
$sql = "UPDATE articles SET clicks=clicks+1 WHERE article_id = :article_id";
$sth = $pdo->prepare($sql);
$sth->bindParam(':article_id', $article_id);
$sth->execute();
}
header('Location: view_article.php?id='.intval($_GET['id']));
?>
As this code is working flawlessly, for MY purposes, here's a little caveat for those looking to just blindly cut-and-paste...it updates the clicks column EACH TIME IT'S CLICKED, soooooo if you need to limit it to a certain amount of clicks or some other type of functionality, I wish you well in your endeavors (lol!). I just wanted to publish this as a current, working model of the PDO kind. In fact, I may have to end up using this solution as a basis of another mind-bending jam I'm in right now. In fact, I'm almost willing to bet dollars to donuts I'll be completely right about this move.
HTHSO
P.S. ...PDO is sooooooo annoyingly difficult...but worth it.

Categories