PHP Data sorting - php

For a statistics table, I am pulling the data to be the last 5 records with DESC over SQL. But the data I shoot comes in the form of 6,5,4,3,2. When I take it as ASC, I get the first 5 records instead of the last 5 records. Take the last 5 records by sorting the data I want to make as 2,3,4,5,6
The function I use
$query = $db->query("SELECT * FROM `table` WHERE `username`='".$username."' ORDER BY id DESC LIMIT 5")
In summary ; The last data I pulled as ASC is listed upside down on the Chart, I want it to be sorted as 2,3,4,5,6
The result I got now

If you need to sort will be done in MySQL can use next:
SELECT tmp.* FROM (
SELECT *
FROM `table`
WHERE `username`='".$username."'
ORDER BY id DESC LIMIT 5
) tmp
ORDER BY tmp.id ASC;

If you're just pulling a small set, just use PHP built in functions like sort or any other function (https://www.php.net/manual/en/array.sorting.php)
If it is a large data set, i'd avoid try to do that directly on the query, something like this:
$db->bind('username',$username);
$query = $db->query('
SELECT * FROM (
SELECT * FROM `table` WHERE `username` = :username ORDER BY id DESC
) qry ORDER BY id'
);
I didnt test the query, but i would something similar to this.

Related

Mysql select last 20 rows, with while loop

I have 50+ rows and each have an id, how do i get the last 20 records and display each ones information with php.
Is the best way to use a loop? I want it to display the results quick and not miss any rows, is a loop the best way to go then?
This is the code that I have
$result = $mysqli_log->query("SELECT * FROM `$usern`");
while( $row = $result->fetch_array() ) {
$credit = $row['credit'];
echo $credit;
}
The MySQL query being executed doesn't specify any "order" to the rows; MySQL is free to return the rows in any order it chooses, so it's possible that the "last 20" rows on one run of the query might differ from the "last 20" rows on a second run.
(We do observe repeated behavior when the statement is re-executed; it usually takes some DML operations, the addition of an index, or an OPTIMIZE table statement, to actually get a change in the results returned... but the point is, there is no "last 20" rows in the table. In MySQL, it's just a set of rows.)
To specify a specific sequence of the rows, add an ORDER BY clause to the query. Assuming that you want to use the unique id column to order the rows, and you want the last 20 rows, and you want them returned in ascending id sequence:
SELECT t.*
FROM ( SELECT u.*
FROM `$usern` u
ORDER BY u.id DESC
LIMIT 20
) t
ORDER BY t.id
And, yes, processing rows "in a loop" in PHP, just like you demonstrate, is a normative pattern.
To limit the number of queries use Limit and order them desc by your ID
Select *
From `$usern`
Order By ID Desc
Limit 20
To Flip them back in the forward order you can use a derived table
Select *
From (Select ID, Test
From test
Order By ID Desc
Limit 3) d
Order By ID Asc
If you need the newest 20 records, you have to ORDER DESC the result set by ID and then LIMIT that set result to 20 records.
So you can
use something like this:
$result = $mysqli_log->query("SELECT * FROM `$usern` ORDER BY `ID` DESC LIMIT 20");
while( $row = $result->fetch_array() ) {
$credit = $row['credit'];
echo $credit;
}
Another good approach, if you are using associative keys like $row['credit'], is to use featch_assoc instead of featch_array (if your framework provides such a function)

Negative limiter MySQL

My code get the last 10 values from a table. This table has te structure id,text and by the moment it has 20 rows. I use this piece of code
<?php
$query = mysql_query("SELECT * FROM `table` ORDER BY `id` DESC LIMIT 10");
// Fetching data stuff here
?>
and it returns the data for IDs 11-20. (The last 10 of the 20)
I want to get the previous 10 values from this 1-10 via AJAX. I thought maybe this will work
$previous_id= $_GET["last"]; // This time it will be 11
mysql_query("SELECT * FROM `table` ORDER BY `id` DESC LIMIT $previous_id, -10");
But I'm doesn't, any suggestion?
Thanks
PS: This is not a gimme teh codez question, I just want to know how to make that query work.
If I understand you correctly you want to get the 10 rows before the row with id = $previous_id, ordered by descending ID.
If that's the case your best bet would be to use a WHERE condition. As you are ordering by id DESC you want the first 10 rows with id > $previous_id:
SELECT * FROM `table` WHERE `id` > $previous_id ORDER BY `id` DESC LIMIT 10
These will be the 10 rows before $previous_id in your original query.
Simply use positive number instead of -10:
"SELECT * FROM `table` ORDER BY `id` DESC LIMIT $previous_id, 10"
Let's suppose $previous_id is 5, the query would be:
"SELECT * FROM `table` ORDER BY `id` DESC LIMIT 5, 10"
The returned rows will be starting from 5 and 10 records.

How do I fetch the last 15 rows in a table, then the 15 before that?

I want to return only the last 15 rows in my table, then the 15 before that.
Unfortunately while($rows = mysql_fetch_assoc($result)) where the query is SELECT * FROM table returns the data in all rows.
I thought about doing something like:
In my insert script
SELECT * FROM table then $selection_id = mysql_num_rows($result)-14 before inserting any data, then adding column named selection_id which would contain $selection_id, thus each set of 15 rows would have the same selection_id.
In my select script
SELECT * FROM table then $num_rows = mysql_num_rows($result)/15 then SELECT * FROM table WHERE selection_id='$num_rows' and SELECT * FROM table WHERE selection_id='$num_rows-1'.
I could then perform while(..) on both results as usual.
However, I'm not sure this is the most efficient way (chances are it's not), so if not, I'd really appreciate some suggestions to cut down the amount of code I'll have to use :)!!
Use a LIMIT clause in your query, order by your auto-incrementing primary key in descending order. E.g.
SELECT * FROM `table` ORDER BY `selection_id` DESC LIMIT 0,15
...will get the last 15 rows, and:
SELECT * FROM `table` ORDER BY `selection_id` DESC LIMIT 15,15
...will get the 15 rows before that.
Selecting the last 15 rows:
SELECT *
FROM `table`
ORDER BY `id` DESC
LIMIT 0,15
Selecting the 15 rows before the previous ones:
SELECT *
FROM `table`
ORDER BY `id` DESC
LIMIT 15,15
And you can continue in a while cycle.
You need to check out mysql LIMIT. To get the last 15, you'd need to know the number of total rows.
$offset=$rowcount-15;
$sql="SELECT * FROM mytable LIMIT $offset,15";
This is just for example, you'd want to make sure there are at least 15 rows, I'm not sure how mysql would deal with a negative offset. I'll let you figure out how to count the rows.
Edit:
Oh, haha, you could also just sort it descending, that will save you having to query twice.
SELECT * FROM mytable ORDER BY id DESC LIMIT 15;

Simplest way to get the next Row from an SQL table when I know the second one

Hi everyone I am trying to write a sorting script
For this my user will click a move up button which posts the id of the current selection we want to move up to a new page where the script is processed.
So using the fetch functions below i am getting the sort id of the current row we want to move up
$sqlCurrent = "SELECT * FROM `contact` WHERE `contact_id` = $id LIMIT 0, 1 ";
$resultsCurrent= mysql_query($sqlCurrent) or die(mysql_error());
$rowC = mysql_fetch_row($resultsCurrent);
$currentSort =$rowC[9];
I then pulled out all the data in decending order using
Now if my current sort order is 6 I want to look for the row with the sort order with 3 or 4 or 5 in order so i used the decending order and the next sort scrip comes up in the next table.
$sql = "SELECT * FROM `contact` ORDER BY `contact`.`contact_sortOrder` DESC LIMIT 0, 30 ";
The question is how do I simply get data from that row using 1 or maybe 2 functions.
We cant simply look for the next sort order because it is possible it wont be there.
For this example i have used a database like this
rowId 1 Sort order 6
rowId 2 Sort Order 2
rowId 3 Sort Order 4
Now I am row Id 3 and want to replace it with the next one. So i need to pick up rowId 2 somehow using the shortest method.
Any help will be useful
Could be as simple as
$query = "
SELECT
x,y,z
FROM
contact
WHERE
contact_sortOrder < $currentSort
LIMIT
1
";
(assuming $currentSort is safe for "direct insertion" into the query. see http://docs.php.net/pdo.prepared-statements)
select prev.*
from contact as curr
left join contact as prev on prev.contact_sortOrder < curr.contact_sortOrder
where curr.contact_id = $id
order by prev.contact_sortOrder desc
limit 1

Get Latest Entry from Database

How can I get the latest entry by the latest DATE field from a MySQL database using PHP?
The rows will not be in order of date, so I can't just take the first or last row.
You want the ORDER BY clause, and perhaps the LIMIT clause.
$query = 'SELECT * FROM `table` ORDER BY `date` DESC LIMIT 1';
SELECT * FROM [Table] ORDER BY [dateColumn] DESC
If you want only the first row:
In T-SQL:
SELECT TOP(1) * FROM [Table] ORDER BY [dateColumn] DESC
In MySQL:
SELECT * FROM `Table` ORDER BY `dateColumn` DESC LIMIT 1
You don't have a unique recordid or date revised field you could key in on? I always have at least an auto incrementing numeric field in addition to data created and date revised fields. Are you sure there is nothing you can key in on?
SELECT * FROM table ORDER BY recno DESC LIMIT 1;
or
SELECT * FROM table ORDER BY date_revised DESC LIMIT 1;
So the PHP call would be:
$result = mysql_query("SELECT * FROM table ORDER BY date_revised DESC LIMIT 1");
-- Nicholas
You can use a combination of the LIMIT and ORDER BY clauses.
For example:
SELECT * FROM entries ORDER BY timestamp DESC LIMIT 1

Categories