Displaying items from multiple tables on your webpage using php while loop - php

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.

Related

How can i display the 5 latests results from the database at the bottom of the page in PHP instead of displaying it at the top?

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

shuffle : Display only one row at the same time

How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.

Multiple PHP/MYSQL WHERE statements, same action for each

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.

select random unique records from mysql db using php

i am trying to fetch random records from mysql database , which it worked but i need the records to be also unique when i fetch them as they duplicated on the output, here is my code:
<?
for ($counter = 1; $counter <=5;$counter++)
{
$randomPostSelect = mysql_query("SELECT DISTINCT * FROM beventreservation WHERE (beventStatus='online' OR beventStatus='soldout') ORDER BY RAND() LIMIT 5") or die(mysql_error());
$fetchPosts = mysql_fetch_array($randomPostSelect) or die(mysql_error());
echo '<li>'.$fetchPosts['eventTitle'].'</li>';
echo '</br>';
}
?>
how can i do that ?
You have all the code in a for loop including the code that runs the query; you "extract" 5 rows from db but only fetch the first, and repeat this 5 times. Instead you should run the query once, then loop on your results until you reach the end of the results:
<?
$randomPostSelect = mysql_query("SELECT DISTINCT * FROM beventreservation
WHERE (beventStatus='online' OR beventStatus='soldout') ORDER BY RAND() LIMIT 5")
or die(mysql_error());
while ($fetchPosts = mysql_fetch_array($randomPostSelect))
{
echo '<li><a href="reservation.php?rev='.$fetchPosts['eventId'].'">'.$fetchPosts['eventTitle']
.'</a </li>';
echo '</br>';
}
?>

only echoing the last 4 things inserted into a MYSQL database

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

Categories