PHP and MYSQL get random row in table - php

Hello I have the following code which returns the amount of rows in a table and the picks a random number between 1 and the amount of rows. I want to be able to get the row in the MySQL table that corresponds to the random number. So if the number is two, I want to get the second row down.
Here is my code so far:
$query = mysql_query("SELECT count(*) as total from videos");
$result = mysql_fetch_array($query);
$TotalCount = $result['total'];
$RandRow = mt_rand(1,$TotalCount);
I do have a id column but all the id's are not in order it goes like this for example: 4, 27, 43, 2, 18, 109, So i cant use that. How can I get a row in a table that corresponds to my random number?

You want one random row out of your table, right? Then you could use ORDER BY RAND() in your query and LIMIT 1. It sorts - surprise - randomly and only returns one dataset.
e.g.
$query = mysql_query("SELECT * FROM videos ORDER BY RAND() LIMIT 1");
So you just have to do one query.

$query = mysql_query("SELECT id from videos");
$ids = array()
While($row=mysql_fetch_array($query)){
$ids[] =$row['id']
}
$RandRow = array_rand($ids,1);
You can fetch all rows ids as an array and select a random one from array by array_rand

Related

Flagging last overall row in MySQL query using LIMIT

I am retrieving results from a database in batches of 5, each time taking the last 'id' and returning it via jquery so only rows with smaller 'id' are returned. I have a load more button which should disappear after all rows are loaded, even if that means 5, 7 or 11 rows.
I have this query:
$query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5");
$query->execute([$_POST["id"]]);
while($row = $query -> fetch()) {
echo "<div id="$row["id"].">".$row["name"]."</div>";
});
The question is, is there an easy and performant way to add a column to flag each row if it's last or not in a single query? Considering I am using LIMIT of 5, obviously the query should also check the potential existence of 5+1 row.
Set the limit to 6 and check the number of returned rows.
for the while loop, use a counter:
$query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 6");
$query->execute([$_POST["id"]]);
$n=5;
while($row = $query -> fetch() && $n-->0)
{
echo "<div id="$row["id"].">".$row["name"]."</div>";
}

How to get the position of a row when a MYSQL table is ordered

I want to find the position of a row when I order the table in a descending order. I used the following to order the rows in a descending order.
SELECT * FROM feature Order BY Votes DESC
I need to find what position the row is in compared to others, such as 1st, 5th, 8th...
I was thinking of using a loop that loops through each value in the ordered from greatest to lowest and if the votes are greater than the previous value but more than the next value, then the position can be found. However, I found this to be impractical if there are many rows in the table. How can I find the relative standing of a row? A simple direction will be sufficient.
If I understand correctly, you could loop through the result as an assoc array, with an $i variable increased each iteration. That $i variable would tell you each row's position in order.
$query = "SELECT * FROM feature Order BY Votes DESC";
$result = mysqli_query($connect, $query);
$i = 1;
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['idColumnName'];
if ($id == 'idNumber'){
echo("My ID is: ".$id." and I am voted number: ".$i);
}
$i++;
}

mysql return numbers of specific row?

In my mysql table i have table that contain points, a want to return number of that table?
Can some one help me?
("select * from liv_sr")
Table contain(id,name,ip,port,*rank*....)
I want to "rank" return in numbers, specifik number
Etc.(1,2,3,500)
query[0]['rank']=1200 points=>1 on rank
query[1]['rank']=800 points=>2 on rank
query[2]['rank']=1 points=>500 on rank
You need to use a order by query
$sql="select * from table order by rank desc";
$point =1;
$result = mysql_query($sql);
$tableResult = array();
while($arrayresult =mysql_fetch_array($result))
{
$tableResult[] = array('id'=>$arrayresult['id'],'rank'=>$arrayresult['rank'],'point'=>$point);
$point= $point+1;
}
Don't know if this is already answered, but if you really want to achieve having only one result row, you could have a look at MySQL group_concat. In your example, you could get a result of say for example:
"1200, 600, 500" (comma seperated, ordered by ranked) with
SELECT GROUP_CONCAT(rank ORDER BY rank DESC SEPARATOR ', ') FROM liv_sr GROUP BY 'all'
In php, you could split the result with:
$myArray = explode(',', $result);
Also, note that there's 1024 byte limit on result. If you need more, than simple run:
SET group_concat_max_len = 2048

Random data mysql

I have table in mysqli database now i want to get 1 result random
This is code mysql
$cid = $_GET['id'];
$ans = $db->query("select * from result where cat_id='$cid' limit 1");
$rowans = $ans->fetch_object();
echo"
<h4>".$rowans->title."</h4><br>
<img src='".$rowans->img."' style='width:400px;height:300;' />
<p>".$rowans->desc."</p>";
in this code i get 1 result but not random always gives me the same result
SQL:
SELECT *
FROM result
ORDER BY rand()
LIMIT 1
LIMIT orders the rows by the primary key of the table, so you always get the same one (the "first" row according to that key).
Try:
SELECT * FROM result WHERE cat_id='$cid' ORDER BY RAND() LIMIT 0,1;
You can think of it this way: it first orders the results by a random order, then picks the first one.

saving a column in an array

I'm trying to fetch random no. of entries from a database by using
SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10
it returns a column of database.
If I want to save all the entries in a array, then which php function do I have to use to save the column.
Something along the lines of this?
$result = mysql_query("SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10");
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row[0];
}
Updated to not use the $i variable as pointed out in the first post and the comment.
Look at some examples for how to run a query and get a result set.
http://www.php.net/mysqli
Once you have the result in a variable, do this:
$myarray = array();
while($row = mysqli_fetch_row($result))
$myarray[] = $row[0];
With PDO:
$qryStmt = $dbc->query('SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10');
$a = $qryStmt->fetchAll( PDO::FETCH_COLUMN );
BTW: If you just want to get one row by random, this is much faster esp. for large tables:
select * from table limit 12345,1;
where 12345 is just a random number calculated from the count() of rows.
see here, which is more for rails, but have a look at the comments too.
But be careful: in limit 12345,2 - the second row is not random but just the next row after the random row. And be careful: When I remember right (eg. SQLServer) rand() could be optimized by databases other than mysql resulting in the same random number for all rows which makes the result not random. This is important, when your code should be database agnostic.
a last one: do not mix up "random" with "hard to predict", which is not the same. So the order by example "select top 10 ... order by rand()" on SQLServer results in two different result sets when run twice, BUT: if you look at the 10 records, they lie close to each other in the db, which means, they are not random.

Categories