How to echo random data - php

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

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

How to mysqli_fetch_row while using mysqli_multi_query

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

Error in fetching rows from table using SQL

This code was working fine yesterday , and suddenly started showing error today..
The die('Error') gives out error when displaying the users with profile pictures
Thanks in advance for the help ... i am learning php so will convert to pdo later
<?php
include("dbconfig.php");
// Create connection
$conn=mysql_connect($db_host,$username,$password) or die('Error1');;
mysql_select_db("motorklq_glmindb",$conn) or die('Error2');
$result = mysql_query("SELECT adno,fname,lname,profilepic,gscore FROM gtable WHERE contest!='on' ORDER BY gscore DESC LIMIT 3") or die('Error');;
echo "<table><tr><th></th><th>gScore Leader</th><th></th><th></th></tr>";
echo "<tr><th>Firstname</th><th>Lastname</th><th>Image</th><th>Glamour</th></tr>";
while($row = mysql_fetch_array($result)){
print "<tr><td>".$row['fname']."</td><td>".$row['lname']."</td><td>".'<img src="data:image/jpeg;base64,' . base64_encode( $row['profilepic'] ) . '" width="32" height="32">'."</td><td>".$row['gscore']."</td></tr>";
}
print "</table>";
mysql_close($conn);
?>
Link to the db https://www.dropbox.com/s/dv8vhla0fxhw2p7/db.png
SELECT adno,
Change to
SELECT idno,
I think you mis-typed adno for idno in your select query.
Hope that helps
delete extra ; from query
$conn=mysql_connect($db_host,$username,$password) or die('Error1');;
$result = mysql_query("SELECT adno,fname,lname,profilepic,gscore FROM gtable WHERE contest!='on' ORDER BY gscore DESC LIMIT 3") or die('Error');;
to
$conn=mysql_connect($db_host,$username,$password) or die('Error1');
$result = mysql_query("SELECT idno,fname,lname,profilepic,gscore FROM gtable WHERE contest!='on' ORDER BY gscore DESC LIMIT 3") or die('Error');

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

echo random id numbers from mysql database without repeating numbers?

How do I echo random id numbers from mysql database without repeating numbers?
this is my sample code:
$query = mysql_query("SELECT * FROM store");
$number=mysql_num_rows($query);
for ($count=1; $count<= $number ; $count++)
{
$id = mysql_query ("SELECT id FROM store ORDER BY RAND() LIMIT $number");
$id = mysql_fetch_assoc($id);
$id = $id['id'];
echo $id;
}
It will echo six random numbers but have instances like "1 1 3 2 4 5" where 1 is echoed twice instead of once. thanks in advance
Just order your results by rand and limit their number, your id has to be unique :
SELECT * FROM store ORDER BY RAND() LIMIT 0,6
The Problem is, that you do a SELECT inside of the loop, instead of selecting once and loop over the result.
$query = mysql_query("SELECT * FROM store");
$number=mysql_num_rows($query);
$result = mysql_query ("SELECT id FROM store ORDER BY RAND() LIMIT $number");
while ($row = mysql_fetch_assoc($result)) {
echo $row["id"];
}
BTW: SELECT * to get the number of recordsets is ugly, use SELECT count(id)instead
If you're coming out of php you're probably better off (faster, easier, no locking issues) to randomize your numbers there. And SQL queries inside loops is an antipattern.

Categories