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.
Related
$query_importer1 = "SELECT * FROM items where item_id ='".$row1["item_id"]."'limit 5 ";
$result_importer1 = mysqli_query($conn,$query_importer1);
for ($i=0; $i<=mysqli_num_rows($result_importer1); $i++)
{
$row = mysqli_fetch_assoc($result_importer1);
echo ''.$row['item_name'].'<br>';
}
i want all item name but its printing only one
You do not need to execute for loop on records, You can get all records using while loop, Plz refer below code
$query_importer1 = "SELECT * FROM items where item_id ='".$row1["item_id"]."' limit 5 ";
$result_importer1 = mysqli_query($conn,$query_importer1);
while($row = mysqli_fetch_assoc($result_importer1)){
echo $row['item_name'];
}
Maybe I am overthinking this, but I have narrowed my query to find a row down to 1 result that I need, and it will not display. Wondering if someone could tell me what I am doing wrong.
$result = mysqli_query($link, "SELECT pageid FROM article ORDER BY id DESC LIMIT 1");
$row = mysqli_use_result($result);
echo $row;
I have it selecting the last row and supplying me with the stored data from the pageid of the last row.
I had to adapt my code. I believe it was because I use mysql. However, this code will work if you use mysqli
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
if ($resultpageid->num_rows > 0) {
while ($row = $resultpageid->fetch_assoc()) {
$pagenumber = $row["pageid"];
}
} else {
echo "0 results";
}
mysqli doesn't have any function to get a single column from a single row. You need to use one of the fetch methods e.g. fetch_array(). You don't need any loop if you use LIMIT 1.
Just fetch a single row and get the column from the returned array:
$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);
$row = $resultpageid->fetch_assoc();
// or
$row = $resultpageid->fetch_array();
if ($row) {
echo $row["pageid"];
} else {
echo "No record found!";
}
Hi im trying to get 5 random rows from a database and then display them. i currently do this but it does result in duplicates.
i need to change the limit to 5 and then store them in an array but how do i do that? or is there a better way?
function GetPlayer($link){
if (isset($_SESSION['username'])) {
$x = 0;
while($x <= 5) {
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 1; ";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_assoc($result);
if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
echo ("<tr>");
echo ("<th>".$row['username']." </th>");
echo ("<th>Level: ".$row['Level']." </th>");
echo ("<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>");
echo ("<th>Win Chance: ");
echo CalculateWinChance($link,$row['Defence']);
echo ("<th><input type ='submit' name = 'Attack_Btn' value ='Attack'></th>");
echo ("</tr>");
$x++;
}
}
}
}
Why dont't you try to request 5 results (LIMIT 5) AND loop this? It will no return any duplicates. Four queries less would be a side effect.
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
while($row = mysqli_fetch_assoc($result)){
...
}
Instead of calling the query 5 times within the loop, you should have a single query. That's the most optimal approach.
You can use GROUP BY clause to select unique rows.
Your query should be like the following:
SELECT *
FROM userstats
GROUP BY username
ORDER BY RAND()
LIMIT 5
You'll want to sanitize the inputs in the query and/or use a prepared statement, but this should get you pretty close to what you want:
$sql = 'SELECT * FROM userstats WHERE username != ? GROUP BY username ORDER BY RAND() LIMIT 5';
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_SESSION['username']);
I have the following code to pull a random value from a database.
$result = mysqli_query($con,"SELECT column1 FROM table1
ORDER BY RAND()
LIMIT 1");
while($row = mysqli_fetch_array($result))
{
echo $row['column1'];
echo "<br>";
}
At the moment I only have about 10 values in total. Sometimes they appear more than once in a row upon refresh.
Can the query be amended to show a random value that is not the current value?
in order to do that you need to somehow remember the last row.
Then do something like this
$result = mysqli_query($con,"SELECT column1 FROM table1
where id_of_your_row != ".mysqli_real_escape_string($id_of_your_last_row)."
ORDER BY RAND()
LIMIT 1");
For remembering the last row, you could use sessions.
Your whole code could look like this.
// sessions need to bestarted
$result = mysqli_query($con,"SELECT column1 FROM table1
where column1 != ".(isset($_SESSION["lastid"]) ? mysqli_real_escape_string($_SESSION["lastid"]) : '')." ORDER BY RAND()
LIMIT 1");
while($row = mysqli_fetch_array($result))
{
echo $row['column1'];
$_SESSION["lastid"] = $row['column1'];
echo "<br>";
}
I am trying to print the duplicate records of the table but only the single row is getting
echoed.However in mysql this query results all the duplicate records. Here is the query:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
$r = mysql_fetch_array($q);
$s = mysql_num_rows($q);
while($s !=0)
{
echo $r;
$s=$s-1;
}
Whats wrong with the code?
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
while($r = mysql_fetch_array($q))
{
print_r($r);
}
You need to loop through the entire record set... you are only grabbing the first row:
$resultset = mysql_query("select * from add where cust_id = '144' group by cust_id");
while($row = mysql_fetch_assoc($resultset))
{
echo $row['column_name'];
}
Your SQL query will in practice only ever return 0 or 1 rows, due to the GROUP BY clause. Are you absolutely sure that that's the query you were executing in mysql?
well, if you want to get duplicate values, then this query will serve you well:
T = the table
f = the field to check for duplicates
id = the rows id
select id,f from T group by f having count(f)= 2;
or >2 if you want every value in f that occurs in more than one row.
having is like where but evaluated after group by.
Try the following:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144'");
while($r = mysql_fetch_array($q))
{
echo $r;
}