while($data=$SQL->fetch(PDO::FETCH_ASSOC)){
echo $data=['message'];
}
is that possible to reverse while loop?
I have a page echo out messages and I need put in reverse
SQL- DESC LIMIT 20
fetch last 20 messages
but my chat box is print in reverse
message 1 (oldest message)
message 2
message 3 (newest message)
You should define the order of the data set in your original SQL query.
See documentation for the ORDER BY clause.
Update
It seems that the OP wants the 20 newest messages, but ordered in reverse. Then you need to perform a subquery like this:
SELECT `message`
FROM (SELECT * FROM `table`
ORDER BY `id` DESC
LIMIT 20) AS `i`
ORDER BY `i`.`id` ASC;
After fetching records You can just reverse your returned array
http://us1.php.net/array_reverse
If you really want to reverse the data in PHP, you can use array_reverse:
// Fetch all records
$data = $SQL->fetchAll(PDO::FETCH_ASSOC);
// Reverse them
$data = array_reverse($data);
foreach ($data as $record) {
echo $record['message'];
}
Although I would recommend ordering in SQL, as it will be faster.
Related
$active_sth = $dbh->prepare("SELECT * FROM user_campaign
WHERE status='blasting'
OR status='ready'
OR status='followup_hold'
OR status='initial_hold'
AND uid=:uid
ORDER BY status ASC");
$active_sth->bindParam(':uid', $_SESSION['uid']['id']);
$active_sth->execute();
I am positive $_SESSION['uid']['id'] = 7
but it will also pull results of id 10 or any other number.
Is my AND/OR clause written wrong?
Yes, query is wrong
SELECT * FROM user_campaign
WHERE (
status='blasting'
OR status='ready'
OR status='followup_hold'
OR status='initial_hold'
)
AND uid=:uid
ORDER BY status ASC
You have to group all ORs to make sure that row got one of this values, and separately check if it have given uid.
The proper way to write that is:
SELECT * FROM user_campaign
WHERE status IN ('blasting', 'ready', 'followup_hold', 'initial_hold')
AND uid =: uid
ORDER BY status ASC
You should use IN instead of that huge amount of ORs :)
I have a table as below,
ID Name Age
----------------------
100 A 10
203 B 20
Now how do i select only row1 using MySQL SELECT command and then I've to increase +1 to it to select row2. In short I'll be using for loop to do certain operations.
Thanks.
Sounds like you've got a mix up. You want to select all the rows you want to iterate through in your for loop with your query, and then iterate through them one by one using php's mysql functions like mysql_fetch_row
You should not try to use tables in a linear fashion like this. Set your criteria, sorting as appropriate, and then to select the next row use your existing criteria and limit it to one row.
SELECT * FROM `table` ORDER BY `ID` LIMIT 1
SELECT * FROM `table` ORDER BY `ID` WHERE ID > 100 LIMIT 1
You'd probably be better off retrieving all rows that you need, then using this. Note the LIMIT is entirely optional.
$query = mysql_query(' SELECT ID, Name, Age FROM table_name WHERE condition LIMIT max_number_you_want '))
while ($row = mysql_fetch_assoc($query)
{
// Do stuff
// $row['ID'], $row['Name'], $row['Age']
}
Lots of small queries to the database will execute much slower than one decent-sized one.
You should get the result into an array (php.net : mysql_fetch_*).
And after you'll can loop on the array "to do certain operations"
Yep, this is a pretty common thing to do in PHP. Like the others who have posted, here is my version (using objects instead of arrays):
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_object($result)) {
// Results are now in the $row variable.
// ex: $row->ID, $row->Name, $row->Age
}
I have a database with nearly 100 fields.
DB structure is
id | comment | time
I need to fetch only 5 newest record (I can get those records using ORDER by time DESC). But while printing them I need to print the oldest of those 5 records first and proceed in reverse in a way that the newest record will be printed last.
SELECT s.* FROM (
SELECT id, comment, time FROM table1
ORDER BY time DESC
LIMIT 5 ) as s
ORDER BY s.time ASC
Ok, after fetching result set in ascending order with a limit of number of rows
you can do this to print them in reverse order (descending order)
$data= array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
$records = array_reverse($data);
OR
This could be done with mysql_data_seek
Directly taken from here
for ($i = mysql_num_rows($resultset) ā 1; $i >= 0; $iā) {
mysql_data_seek($resultset, $i);
$row = mysql_fetch_assoc($result);
echo $row['abc'] . ' ' . $row['xyz'] . "\n";
}
You can use PHP's array_reverse() function on your result list.
http://php.net/manual/en/function.array-reverse.php
You can use also something like this:
select * from (select * from table_name where 1=1 order by time desc
limit 5) as tbl order by tbl.time;
Edit if you have a lot of accesses to this statement it would be much better to represent it as materialized view. Though there are no materialized views in mysql it is possible to simulate them (http://lists.mysql.com/mysql/207808)
Using a materialized view or a simulated materialized view will seriously outperform the suggested php approaches. Most of the mentioned ones consume to much memory anyways .
I guess you could do something along the lines of (untested):
SELECT
*
FROM (
SELECT
id, comment, time
FROM
table
ORDER BY
time DESC
LIMIT 5
)
ORDER BY
time ASC
UPDATE
Apparently, the "derived table must have its own alias" (error #1248). Other answers have already done this, so I'll jump on the bandwagon. Below you'll find the revised (and tested) query:
SELECT
derived.*
FROM (
SELECT
id, comment, time
FROM
table
ORDER BY
time DESC
LIMIT 5
) AS derived
ORDER BY
derived.time ASC
By the way, this is supported as of MySQL 4.1.
i have a fetch row query that returns
10 9 8 7 6 5 4 3 2 1
however, i only want to return the last value, which is "1" in this case.
i tried to do echo row[0][9] but it doesn't work.
how do i get the last value?
you can use the end() function
$row = array(10, 9, 8, 7);
echo end($row); // displays 7
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Take a look # this example. Copied from here. You should be able to achieve what you wanted by taking a look at the above example.
If you know what the column index is, you are good to go. But if you ALWAYS want the last column take a look at the mysql_num_fields function.
Try echo explode(' ', $row[0])[9]
Been a while since I've done PHP though, YMMV.
you must sort your table by DESC keyword .
I'd do it all on MySQL side, so you don't split the logic between PHP and MySQL too much (if that's applicable in this case) and use query with LIMIT 1 and ORDER BY DESC (or ASC, depending on your table).
You only want the 10th last row that was added to the table? That would be the 10th id in the list if you sort by id descending. If that's what you want, you also could tell MySQL to return exactly that row. The query gets a bit more complicated though:
SELECT t1.*
FROM table t1
INNER JOIN (
SELECT id
FROM table
ORDER BY id DESC
LIMIT 10
) t2 ON t1.id = t2.id
ORDER BY t1.id ASC
LIMIT 1
Here's my code.
$query="SELECT blog_id FROM myblogs_view where blog_id<'$id' ORDER BY blog_id DESC LIMIT 10";
$result=mysql_query($query);
while($row=mysql_fetch_row($result) or die(mysql_error())) {
echo $row;
}
This returns the values in one row. how do i access the value in the last row only?
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'];