Random data mysql - php

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.

Related

Use PHP mt_rand() instead of MySQL rand() to avoid slow query

I have a PHP file that looks for a random id from a MySQL DB, but when the table is big enough it gets slow.
ID row has gaps.
Original
$sql = "SELECT * FROM definiciones ORDER BY rand() LIMIT 1";
Idea
$random = mt_rand(0, 10000);
$sql = "SELECT * FROM definiciones WHERE id = (SELECT max(id) FROM definitiones WHERE id < $random)";
I know the exact amount of rows in the DB beforehand. Is it a good idea to replace the original query?
Is it a good idea to replace the original query?
Yes, but there's a simpler way of expressing this:
SELECT * FROM definiciones WHERE id >= ? ORDER BY id LIMIT 1
With ? set to a random number between 0 and the maximum ID in the table.
Now, an improvement: If there are any gaps in the values of id, the results from the previous method will be skewed somewhat. (For instance, if there are no rows with id < 100, then a row with id = 100 will be selected much more often than one with id = 101.) You can avoid this by using a separate column for randomization. First, you will need to add the column:
ALTER TABLE definiciones ADD COLUMN randomval FLOAT NOT NULL,
ADD KEY randomval (randomval);
UPDATE TABLE definiciones SET randomval = RAND();
Then, to select a fairly chosen random item:
SELECT * FROM definiciones WHERE randomval > ? LIMIT 1;
using a random value between 0 and 1 for the parameter.
There is a small chance that this will return no rows (if RAND() selects a value greater than the highest value in the table). If this happens, repeat the query.
You will need to set randomval = RAND() when inserting new rows into the table.

How to select the top third row in mysql

Guys am trying to select the top/recently third row, i tried this one but it doesn't work, where do i make mistake ?
<?php
$sql = "SELECT * FROM songs ORDER BY id ASC LIMIT 1,2;";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['artist'];
}
}
?>
Use OFFSET:
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The shorthand (which you are using) is reversed, so OFFSET is first then LIMIT:
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1;
Use OFFSET
Here the limit 1 It simply means and you need one record
and the offset means skip the first 2
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The parameters you use after limit should be reversed.
The first parameter is offset, and the second parameter is number of record you want.
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1
This is just my opinion--
Sorting like this should always be done in client software.
Extract the data - remove the ORDER BY for your SQL...
Sort it in your client, and select and return the third line to the caller.
You will get better scalability and maintainability than driving all of this through an SQL query.
This is my go-to approach when solving these types of problems through custom software and it has been proven out over time.
Think about this:
Select ID from songs
get the id's into your code, and sort them there. Then chose the third one in the list. Then:
select title, author, artist, ... from songs where ID = VALUE FROM ID ABOVE
Yes, you are hitting the database twice, but these are two very efficient queries and that will perform better as your database scales, than the fancy order by you propose.

PHP and MYSQL get random row in table

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

Mysql select list after a specific id

I'm trying to find a solution to select a list of rows coming after a certain Id from an ordered list.
For example, first I select 1000 rows. Then, on a subsequent request, i want to fetch another 1000 rows coming from after the last id of the first request. I know i can do it with limit, but suppose there has been 100 rows added between the first and second request, there will be 100 rows that will be from the first request.
Both queries will be ordered by the date of the entries.
Here's an example of the query I thought of:
$query = "SELECT * FROM table WHERE id AFTER $id ORDER BY date DESC";
$query = "SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT 1000";
Two ways to do this:
WHERE
"SELECT * FROM `table` WHERE `id` > '$id' ORDER BY `date` DESC LIMIT $length"
LIMIT
"SELECT * FROM `table` LIMIT $start, $length"
$query = "SELECT * FROM table WHERE id > $id ORDER BY date LIMIT 1000";
You're asking about logic, not code so here it is.
The first request selects the first 1000.
$query = "SELECT * FROM the_table ORDER BY `date` DESC LIMIT 0,1000";
NB date is a reserved word so needs escaping if you've called a column "date" which you shouldn't.
$rs=$db->selectMany($query); // replace this with however you select the rows. $rs is results set
Do stuff with PHP and save the maximum id. They may not be in order.
$maxid=0;
foreach ($rs as $r){
// whatever you need to do with your results
$maxid=max($maxid, $r->id);
}
Your subsequent select uses the last id
$query = "SELECT * FROM the_table WHERE id > $maxid ORDER BY date DESC LIMIT 0,1000";
BUT you need to take note that you're ordering by date and using id to find a breakpoint which sounds like it would cause data to be missed.
Perhaps you mean to use WHERE`date`> $maxdate? If so you can figure that out from the code given.

How do I fetch the last record in a MySQL database table using PHP?

I want to fetch the last result in MySQL database table using PHP. How would I go about doing this?
I have 2 Columns in the Table, MessageID(auto) & Message.
I already know how to connect to the database.
Use mysql_query:
<?php
$result = mysql_query('SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo $row['messageid'];
echo $row['message'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
The SQL query:
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
...uses the ORDER BY to set the values so the highest value is the first row in the resultset. The LIMIT says that of all those rows, only the first is actually returned in the resultset. Because messageid is auto-increment, the highest value is the most recent one...
Records in a relational database do not have an intrinsic "order" so you cannot fetch the "last" record without some kind of ORDER BY clause.
Therefore, in order to fetch the "last" record, simply reverse the ORDER BY clause (change ASC to DESC or vice versa) then select the first result.
If you have an auto-increment field and you just want to find the last value that was inserted, you can use the fact that the auto-increment fields are ever-increasing (therefore the "last" one will be the one with the highest value) and do something like this:
SELECT *
FROM my_table
ORDER BY id_field DESC
LIMIT 1
Of course you can select the last row by sorting DESC in your query. But what if you want to select the first row and then the last. You can run a new query, but you can also use the function mysql_data_seek. check code below:
$result = mysql_query('YOUR QUERY') or die('Invalid query: ' . mysql_error());
$row_first = mysql_fetch_array($result);
mysql_data_seek($result , (mysql_num_rows($result)-1));
$row_last = mysql_fetch_array($result);
Hope this helps
The MySql query would look like this:
select MessageID, Message
from Table
order by MessageID desc
limit 1;
I am too rusty with PHP to give you the right syntax for executing this.
This query works because you have an auto-incrementing identifying field (MessageID). By ordering the results by that field in descending (largest to smallest) order we are effectively returning the records in the table in reverse order. The limit 1 clause simply limits the result set to one record - the last one in the table.
What do you mean by "the last result"? You need to precise a bit more.
Do you mean "the last entry I registered"?
In this case you should use the appropriate method (depending on the extension you are using) mysqli->insert_id OR mysql_insert_id.
If you mean "the latest entry in the table", an SQL query such as Andrew Hare's is just what you need.
Do you mean the last record or do you need the id of the most recently inserted record? For that you would use the PHP mysql_insert_id() function. Or if you are using the myusqli extension use $mysqli->insert_id.
for some reason (which I don't know why), my boss force me to get the data in this way:
$message_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$message_arr['messageid']= $row['messageid'];
$message_arr['message']= $row['message'];
}
return $message_arr;
Of course, you need everything from OMG Ponies's answer I'm just telling you another way to do it =)
I hope this help.
You should use SELECT query. How SELECT works.
SELECT * FROM table - selects everything in a table (id, row 1, row 2,...)
SELECT id FROM table - selects only particular row from table.
If you now know, how to select, you can use additional logic.
SELECT * FROM table ORDER by id DESC LIMIT 1;
selects everything from table table, orders it by id - orders it DESCENDING and limits the query to only one result.
If you would do it like this:
SELECT * FROM table ORDER by id ASC limit 1; - you would get 1 entry into database.
You can order it by any row you want.
Hope it helps.
One thing to remember is that data does not get saved in the insertion order in any MYSQL database. So in order to get the last entered record u will have to have an auto increment field. Since there is an auto increment field in this table we are good to go.
The below script will help to get the last entered record
<?php
$sql = "SELECT * FROM table_name ORDER BY MessageID DESC LIMIT 2";
$result_set = mysql_query($sql);
if($result_set){
while($row = mysql_fetch_array($result_set)) {
echo "Message Id: ".$row['MessageID']."<br>";
echo "Message: ".$row['Message']."<br>";
}
//creating alert
echo "<script type=\"text/javascript\">alert('Data was Retrieved
successfully');</script>";
}
else{
//creating alert
echo "<script type=\"text/javascript\">alert('ERROR! Could Not Retrieve
Data');</script>";
}
?>
The query selects all the records in the table and orders them according to the descending order of the MessageID (as it is the auto increment field) and limits the returned result to only one record. So since the table is ordered according to the descending order of the MessageID only the last entered record will be returned.
NOTE: if you are using a newer version you will have to use mysqli_query($connection_variable,$sql); instead of mysql_query($sql); and mysqli_fetch_array($result_set) instead of mysql_fetch_array($result_set)
$result = mysql_query('select max(id) from your_table ') or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['id'];
echo $row['message'];
}
//
//
mysql_free_result($result);
simple like that
this code of php works fine
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
if you don't have concurrent entries going into some table.b'cause concurrent entries may not go in accordance of their insertion order.
$statement = $PDO->prepare("
SELECT MessageID,
Message
FROM myTable
ORDER BY MessageID DESC
LIMIT 1;
");
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
echo $result['MessageID']." and ".$result['Message'];

Categories