ive got this script that echos the information from a mysql database.
now it all works fine but i only want to echo the last 4 statements inserted
this is the script
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("blog") or die(mysql_error());
$result = mysql_query("SELECT * FROM blog")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['username'];
echo "</td></tr>";
}
echo "</table>";
?>
Modify your mysql query (i assume that each entry as an ascending id):
SELECT * FROM blog
ORDER BY id DESC
LIMIT 4;
But this will get them in reverse order. If you want them in correct order you can do:
SELECT *
FROM (
SELECT * FROM blog
ORDER BY id DESC
LIMIT 4
) last_four
ORDER BY id ASC;
If you have an auto-incremented column as an id for each blog post, you could sort on the id in descending order. Use a query like this
mysql_query("SELECT * FROM blog ORDER BY your_id_column DESC LIMIT 4")
Assuming your blog table has a column called created, which contains the post's creation date, this query should do what you need:
SELECT * FROM blog ORDER BY created DESC LIMIT 4
This will order your posts by the most recently created post (time-wise), and will only return the first 4 rows fetched from the table.
You would do this with the query, changing the query to something like:
select * from blog order by blog_id desc limit 4
you'll have to change blog_id to whatever you use.
use this query which will order the records by ID in descending order and fetch only last 4 by using limit.
SELECT * FROM blog order by ID DESC LIMIT 4
You can restrict your SELECT using LIMIT and ORDER BY, but in order to help, we'd need to know a bit more about the database structure. Can you provide the results of "DESCRIBE blog;"?
If your "id" field is set up with auto_increment, then it's a good bet that higher numbers of that field indicate more recent posts. Showing output in reverse order ("ORDER BY id DESC") and restricting the number ("LIMIT 4") should be fairly straightforward.
SELECT * FROM blog ORDER BY id DESC LIMIT 4;
Check out the precise structure of the SELECT command at the MySQL documentation.
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("blog") or die(mysql_error());
$result = mysql_query("SELECT * FROM `blog` ORDER BY `id` DESC LIMIT 4") or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Age</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['username'];
echo "</td></tr>";
}
echo "</table>";
?>
Just copy and paste the code. I believe the code will works good. Thanks
Related
This is my PHP file:
<?php
$sql = "SELECT * FROM `general_chat` ORDER BY `general_chat`.`id` DESC limit 5";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "<p>";
echo "<span class = 'usr'>".$row['user_name']."</span>";
echo "<br>";
echo $row['message'];
echo "<br>";
if($row['Date'] === date("Y-m-d")){
echo "Today ";
}
else{
echo $row['Date'];
}
echo $row['Time'];
echo "</p>";
}
}
else{
echo "No messages were found!";
}
?>
This is how my database table looks:
An image of the database table
And this is how it displays the data in the PHP file:
An image of the PHP file output
It displays the five latest rows at the top, is it possible to flip and make it display it at the first bottom and then display the others on top of it?
I tried using DESC instead of ASC but then it displays the five oldest rows instead of the latest
I am not sure this is a perfect method
but this could solve your problem
select * from (SELECT * FROM `general_chat` ORDER BY `general_chat`.`id` DESC limit 5) G ORDER BY G.id ASC;
This IS wrapping your SQL with a similar one
so in subquery it will fetch all latest 5 items and in main query it will sort by ASC
Try :
$sql = "SELECT * FROM (SELECT * FROM `general_chat` ORDER BY `general_chat`.`id` DESC limit 5) as G ORDER BY `G`.`id` asc";
I'm trying to get the latest info about some specific person, and I'm using a query like
SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID DESC LIMIT 1
and
SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID DESC LIMIT 1
because in the Table each day will insert new data for different person at the instant of updating it (for record reference), so I would like to print out a few persons latest info by "ORDER BY ID DESC LIMIT 1"
I have tried to print it out with "mysqli_multi_query" and "mysqli_fetch_row"
like
$con=mysqli_connect($localhost,$username,$password,'Table');
$sql = "SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID
DESC LIMIT 1 ";
$sql .= "SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID
DESC LIMIT 1";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo '<tr>'; // printing table row
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '<td>'.$row[9].'</td>';
echo '<td>'.$row[10].'</td>';
echo '<td>'.$row[11].'</td>';
echo '<td>'.$row[12].'</td>';
echo '<td>'.$row[13].'</td>';
echo '<td>'.$row[14].'</td>';
echo'</tr>'; // closing table row
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
In the result page , it doesn't show any error message , but no results are printed.
The individual queries were tested.
Please advise, much thanks
Is there another way to keep the query simple, so there is no need to use mysqli_multi_query?
Best practice indicates that you should always endeavor to make the fewest number of calls to the database for any task.
For this reason, a JOIN query is appropriate.
SELECT A.* FROM test A INNER JOIN (SELECT name, MAX(id) AS id FROM test GROUP BY name) B ON A.name=B.name AND A.id=B.id WHERE A.name IN ('Peter','Mary')
This will return the desired rows in one query in a single resultset which can then be iterated and displayed.
Here is an sqlfiddle demo: http://sqlfiddle.com/#!9/2ff063/3
P.s. Don't use LIKE when you are searching for non-variable values. I mean, only use it when _ or % are logically required.
This should work for you:
$con = mysqli_connect($localhost,$username,$password,'Table');
// Make a simple function
function personInfo($con, $sql)
{
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<table>
<tr>';
for($i=0; $i < count($row); $i++) echo '<td>'.$row[$i].'</td>';
echo '</tr>
</table>';
}
}
}
$sql1 = "SELECT * FROM Table WHERE Name='Peter' ORDER BY ID DESC LIMIT 1 ";
$sql2 = "SELECT * FROM Table WHERE Name='Mary' ORDER BY ID DESC LIMIT 1";
// Simply call the function
personInfo($con, $sql1);
personInfo($con, $sql2);
I have the following code, that outputs all data from the comment field, however i wish for it to output only two and for them to be random, how can i got about doing this? many thanks.
$query = mysql_query("SELECT * FROM comments ");
//query the database
echo "<b>Reviews</b> ";
WHILE($rows = mysql_fetch_array($query)):
$comment_by = $rows['comment_by'];
$comment= $rows['comment'];
echo "<div style ='font:14px/21px Arial,tahoma,sans-serif;color:#cf5c3f </h>'>$comment_by</h>";
echo "<div style ='font:14px/21px Arial,tahoma,sans-serif;color:#ff0000 <h></h>'>$comment<br><br>";
endwhile;
?>
Use:
SELECT * FROM comments
ORDER BY RAND()
LIMIT 2
LIMIT 2: for two records
and
ORDER BY RAND(): for random comments
See official MySQL documentation:
ORDER BY: https://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
RAND(): https://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html
LIMIT: https://dev.mysql.com/doc/refman/5.0/en/select.html
From dev.mysql.com
$query = mysql_query("SELECT * FROM comments ORDER BY RAND() LIMIT 2");
Trying to get PHP to read my MYSQL db for transactions, divide them by "category" and print the total for each category.
Using a similar structure as the code below, how can I make it do all of the below for each category number. In my db, categories are a number 1-10.
Any help would be much appreciated!
<?php
$result = mysql_query("SELECT SUM(amount) AS value_sum FROM TRANSACTIONS where category=2")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
echo "<div class='col1'>";
echo round ($row['value_sum'], 2);
echo "</div>";
}
?>
$result = mysql_query("SELECT SUM(amount) AS value_sum
FROM TRANSACTIONS
GROUP BY category");
Now you have a row per category.
I am trying to dsiplay data from 2 different tables from my mysql database using a while loop.
Currently I can display the data from 1 table and limit the results to 3. I then want to display the first 5 records from another table. If I join the tables I can only display the same number of items from both using LIMIT?
I am using a while loop to display the content from a table called item, using the following code;
$query");
$result2 = #mysql_query($query, $connection)
or die ("Unable to perform query$query");
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['item'] ?>
<?php
}
?>
If I start another loop for the data from the next table called movie, however the data is not displayed using the following code;
<?php
while($row= mysql_fetch_array($result2))
{
?>
<?php echo $row['title'] ?>
<?php
}
?>
What is the best way to display the data from the 2 tables?
Many Thanks
I don't know if you forgot to paste a bit of code, but this should work:
<?php
$query = "select * from item order by date, time asc limit 0,3";
$result = mysql_query($query);
while($row= mysql_fetch_array($result))
{
echo $row['item'];
}
$query2 = "select * from movie limit 0,5";
$result2 = mysql_query($query2);
while($row= mysql_fetch_array($result2))
{
echo $row['movie'];
}
?>
You may be able to do it with one SQL Query too:
SELECT i.item, m.movie
FROM (SELECT * FROM item ORDER BY date, time ASC LIMIT 0,3) i,
(SELECT * FROM movie limit 0,5) m
Then in php:
<?php
while($row= mysql_fetch_array($result))
{
echo $row['item'];
echo $row['movie'];
}
?>
But that depends on how you want to format the output.