How to echo MySQL results in inverse order? - php

$result3=mysql_query("select * from $mail");
while($row=mysql_fetch_array($result3)) {
if($row['status']!=NULL) {
echo $row['status'];
echo $row['date'];
echo $row['time'];
}
}
i want that the last field in the database should be displayed first. How to implement this?

$result3 = mysql_query("SELECT * from $mail ORDER BY `date` DESC");
Never do yourself what the database can do for you.
If, for whatever weird reason, you actually want to traverse the result set in reverse order, you'll have to use mysql_data_seek, starting at mysql_num_rows() - 1 and decrementing the pointer after each call to mysql_fetch_array.

Use an ORDER BY clause in your query so that the results come in the order you want to display them.
Without an ORDER BY, there is no guarantee about what order the data will come in, so "reversing" that doesn't make sense.

Either user an ordering in the SQL query itself using ORDER BY or put them into an array in PHP and reverse the array:
$all_rows = array();
while($row=mysql_fetch_array($result3)) {
$all_rows[] = $row;
}
$all_rows = array_reverse($all_rows);

Order your fields with the ORDER BY sql feature. So choose what field you want to order by, and order it by that field..
$result3=mysql_query("select * from $mail ORDER BY date DESC ,time DESC");
or if they have an id field:
$result3=mysql_query("select * from $mail ORDER BY id DESC");
And while you're at it, make sure that you know EXCATLY what is in $mail!

"select * from $mail order by date DESC, time DESC"

Related

Change orders of rows in mysqli_result

For example I have the code
$query="Select * from table order by id";
$res1=mysqli_query($link,$query);
while($row=mysqli_fetch_array($res1)) {
echo $row['Id'];
}
echo '<br>';
$query="Select * from table order by user";
$res1=mysqli_query($link,$query);
while($row=mysqli_fetch_array($res1)) {
echo $row['Id'];
}
It is possible to do this without second query and without use of array and foreach, to change orders of row in resul1 from first query to get order like in second query.
You can easily order by several fields at one time:
$query = "SELECT * FROM table ORDER BY id, user ";
$res1 = mysqli_query($link,$query);
....
you can achieve this by passing a php variable in the mysql query.
$query="Select * from table order by $order";
and set $order as you want.
$query = "SELECT * FROM table ORDER BY id, user ";
This will order your data first by id and then user.
You can change order of results in PHP.
Get all results into a PHP array.
Write a comparison function.
Use usort http://php.net/manual/en/function.usort.php

Echo last entry into MySql table first, followed by the next most previous entry

I have a very simple database table of posts, I'd like to be able to print the most recent entry first, followed then by the next most previous entry etc etc when I retrieve them all . How do I do this?
$someText = mysql_query("SELECT * FROM text");
while($row = mysql_fetch_array($someText)) {
echo "$row[column]";
}
You have to order them by id or date or something else. (ASC or DESC)
This might do the trick if you've added them in the correct order.
$test = mysql_query("SELECT * FROM posts ORDER BY id DESC");
while($row = mysql_fetch_array($test)) {
echo "$row[post]";
}
In your SQL statement, "SELECT * FROM posts ORDER BY <date_time_field> DESC" If you don't have a date_time_field, you can use the primary key (usually id).
If you are just trying to order them by date, the MySQL would be like:
SELECT * FROM posts ORDER BY date DESC

How can I get the last row value with MySQL?

I have a table called Live, and in the table I have public_id. In public_id are numbers (e.g. 1,2,3,4,5). How can I get the highest number or the last entry's number?
I'd choose
SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;
It has already been posted, but i'll add something more:
If you perform this query usually you can create an index with inverted ordering.
Something like:
CREATE INDEX ON Live (public_id DESC)
Please Note
DESC
PHP + MySQL code:
<?php
$result = mysql_query('SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;');
if (mysql_num_rows($result) > 0) {
$max_public_id = mysql_fetch_row($result);
echo $max_public_id[0]; //Here it is
}
?>
SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;
would give you the highest number
Edit: For the php
$conn = mysql_connect(....
$query = "SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1";
$result = mysql_query($query, $conn);
Another option is to use MAX, ie
SELECT MAX(public_id) FROM Live
You can either use ORDER BY public_id DESC LIMIT 1; to obtain the record with the highest id (I guess you are using autoincrement attribute on public_id) or MySQL MAX() function like this:
SELECT * FROM table WHERE public_id = MAX(public_id);
edit:
Here is how you will do it in php:
// executing the QUERY request to MySQL server, mysql_query() returns resource ID
$result = mysql_query('SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1');
// then we use this resource ID to fetch the actual value MySQL have returned
$row = mysql_fetch_array($result, MYSQL_FETCH_ASSOC);
// $row variable now holds all the data we got from MySQL, its an array, so we just output the public_id column value to the screen
echo $row['public_id']; // you can use var_dump($row); to see the whole content of $row

Sort by date (newest)

Right now I'm sorting by each articles auto_increment id with the query below
mysql_query("SELECT * FROM articles ORDER BY id DESC");
I want to know how to sort by a date field I made, that stores the current date via, strtotime() it should query the dates from newest to oldest.
Current code
$alist = mysql_query("SELECT * FROM articles ORDER BY id DESC");
$results = mysql_num_rows($alist);
if ($results > 0){
while($info = mysql_fetch_array($alist)) {
// query stuff
echo $info['time'];
}
Just change the column in the ORDER BY:
SELECT * FROM articles ORDER BY time DESC
Let MySQL handle the date stuff - IMO its MUCH better at it than PHP...
add a column with DATE or DATETIME type in your table. On inserting a new record either use NOW() or set a trigger to do it for you (will have to allow null in the coulmn if you are going to user a trigger)
your query should be:
$alist = mysql_query("SELECT * FROM articles ORDER BY `your_date_field` DESC");

How do I fetch the last record in a MySQL database table using PHP?

I want to fetch the last result in MySQL database table using PHP. How would I go about doing this?
I have 2 Columns in the Table, MessageID(auto) & Message.
I already know how to connect to the database.
Use mysql_query:
<?php
$result = mysql_query('SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo $row['messageid'];
echo $row['message'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
The SQL query:
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
...uses the ORDER BY to set the values so the highest value is the first row in the resultset. The LIMIT says that of all those rows, only the first is actually returned in the resultset. Because messageid is auto-increment, the highest value is the most recent one...
Records in a relational database do not have an intrinsic "order" so you cannot fetch the "last" record without some kind of ORDER BY clause.
Therefore, in order to fetch the "last" record, simply reverse the ORDER BY clause (change ASC to DESC or vice versa) then select the first result.
If you have an auto-increment field and you just want to find the last value that was inserted, you can use the fact that the auto-increment fields are ever-increasing (therefore the "last" one will be the one with the highest value) and do something like this:
SELECT *
FROM my_table
ORDER BY id_field DESC
LIMIT 1
Of course you can select the last row by sorting DESC in your query. But what if you want to select the first row and then the last. You can run a new query, but you can also use the function mysql_data_seek. check code below:
$result = mysql_query('YOUR QUERY') or die('Invalid query: ' . mysql_error());
$row_first = mysql_fetch_array($result);
mysql_data_seek($result , (mysql_num_rows($result)-1));
$row_last = mysql_fetch_array($result);
Hope this helps
The MySql query would look like this:
select MessageID, Message
from Table
order by MessageID desc
limit 1;
I am too rusty with PHP to give you the right syntax for executing this.
This query works because you have an auto-incrementing identifying field (MessageID). By ordering the results by that field in descending (largest to smallest) order we are effectively returning the records in the table in reverse order. The limit 1 clause simply limits the result set to one record - the last one in the table.
What do you mean by "the last result"? You need to precise a bit more.
Do you mean "the last entry I registered"?
In this case you should use the appropriate method (depending on the extension you are using) mysqli->insert_id OR mysql_insert_id.
If you mean "the latest entry in the table", an SQL query such as Andrew Hare's is just what you need.
Do you mean the last record or do you need the id of the most recently inserted record? For that you would use the PHP mysql_insert_id() function. Or if you are using the myusqli extension use $mysqli->insert_id.
for some reason (which I don't know why), my boss force me to get the data in this way:
$message_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$message_arr['messageid']= $row['messageid'];
$message_arr['message']= $row['message'];
}
return $message_arr;
Of course, you need everything from OMG Ponies's answer I'm just telling you another way to do it =)
I hope this help.
You should use SELECT query. How SELECT works.
SELECT * FROM table - selects everything in a table (id, row 1, row 2,...)
SELECT id FROM table - selects only particular row from table.
If you now know, how to select, you can use additional logic.
SELECT * FROM table ORDER by id DESC LIMIT 1;
selects everything from table table, orders it by id - orders it DESCENDING and limits the query to only one result.
If you would do it like this:
SELECT * FROM table ORDER by id ASC limit 1; - you would get 1 entry into database.
You can order it by any row you want.
Hope it helps.
One thing to remember is that data does not get saved in the insertion order in any MYSQL database. So in order to get the last entered record u will have to have an auto increment field. Since there is an auto increment field in this table we are good to go.
The below script will help to get the last entered record
<?php
$sql = "SELECT * FROM table_name ORDER BY MessageID DESC LIMIT 2";
$result_set = mysql_query($sql);
if($result_set){
while($row = mysql_fetch_array($result_set)) {
echo "Message Id: ".$row['MessageID']."<br>";
echo "Message: ".$row['Message']."<br>";
}
//creating alert
echo "<script type=\"text/javascript\">alert('Data was Retrieved
successfully');</script>";
}
else{
//creating alert
echo "<script type=\"text/javascript\">alert('ERROR! Could Not Retrieve
Data');</script>";
}
?>
The query selects all the records in the table and orders them according to the descending order of the MessageID (as it is the auto increment field) and limits the returned result to only one record. So since the table is ordered according to the descending order of the MessageID only the last entered record will be returned.
NOTE: if you are using a newer version you will have to use mysqli_query($connection_variable,$sql); instead of mysql_query($sql); and mysqli_fetch_array($result_set) instead of mysql_fetch_array($result_set)
$result = mysql_query('select max(id) from your_table ') or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['id'];
echo $row['message'];
}
//
//
mysql_free_result($result);
simple like that
this code of php works fine
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
if you don't have concurrent entries going into some table.b'cause concurrent entries may not go in accordance of their insertion order.
$statement = $PDO->prepare("
SELECT MessageID,
Message
FROM myTable
ORDER BY MessageID DESC
LIMIT 1;
");
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
echo $result['MessageID']." and ".$result['Message'];

Categories