How to fetch a random record from SQLite database? - php

I am working on PHP. I was working with MySQL before. Here is the code I used -
$offset_result = mysqli_query($con, " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM students ");
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysqli_query($con, " SELECT name FROM students LIMIT $offset, 1 " );
$row = mysqli_fetch_row($result);
mysqli_free_result($result);
What will be the corresponding set of statements for SQLite?

Those SQL queries should work in SQLite if you just change RAND to RANDOM and FLOOR(x) to CAST(x AS INTEGER).
A slightly simpler way to do it is to order by a random number:
SELECT name
FROM students
ORDER BY RANDOM()
LIMIT 1
The way you are doing it is more efficient if the table is very large.

Related

php pdo select multiple rows and insert to other table with LIMIT

i have 2 tables equip_copy(copyID, equipment_id) and insert it to table
mre_copy (mreID,copyID,equipment_id)
I have tried this Select query but doesnt move. Please anyone can help me?
$display = $con->query("SELECT copyID,equipmentID
FROM equip_copy
WHERE equipmentID= :eid
ORDER BY copyID DESC
LIMIT :elimit");
$display->execute(array("eid" => $id, "elimit"=>$request));
foreach($display as $row){
$newCID = $row['copyID'];
$newEID = $row['equipmentID'];
$sql_table = "INSERT INTO mre_copy(mreID,equipmentID,copyID) values(?,?,?)";
$stmt = $con->prepare($sql_table);
$stmt->execute(array($mreID,$newEID,$newCID));
}
Use insert . . . select. I think this is what you want to do
INSERT INTO mre_copy (mreID, equipmentID, copyID)
SELECT :mreID, copyID, equipmentID
FROM equip_copy
WHERE equipmentID = :eid
ORDER BY copyID DESC
LIMIT :elimit;
I'm not sure where mreID comes from. If it is auto-incremented, then just leave it out of the INSERT altogether.

PHP -- How to select random but different rows from table

I have the following code which selects information from one random row.
$query = mysql_query("SELECT * FROM lines_angles_shapes ORDER BY RAND() LIMIT 1 ");
while($rows = mysql_fetch_array($query))
{
$question = $rows['question'];
$hint = $rows['hint'];
$level = $rows['level'];
$keyword = $rows['keyword'];
$showme = $rows['showme'];
$picture_path = $rows['picture_path'];
}
This works well for me but I now I need to be able to select two more DIFFERENT pictures from the picture_path column and assign them to variables. Again, all three rows need to be different.
Any tips for a newbie on how to do this?
Just change your query as follows:
$query = mysql_query("SELECT * FROM lines_angles_shapes ORDER BY RAND() LIMIT 3");
You are ordering by ORD() so it will give you different records.
No, new modification, just change the limit to 3 (whatever your need).
$query = mysql_query("SELECT * FROM lines_angles_shapes ORDER BY RAND() LIMIT 3");
As your are already getting random values with order by clause it will always return different values so you just need to edit your limit value and you are done!
$query = mysql_query("SELECT * FROM lines_angles_shapes ORDER BY RAND() LIMIT 3");

Fast random row in MySql

I need to generate a random row from my MySql database and i have found example here:
http://akinas.com/pages/en/blog/mysql_random_row/
And i want to use solution 3 which looks like this:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `users` LIMIT $offset, 1 " );
My code looks like this now:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( "SELECT * FROM `users` WHERE profile_image='2' LIMIT $offset, 1 " );
$random_date = mysql_fetch_array($result);
echo $random_date['user_name']; //display username of random user
But when i refresh the page: approximatly 7 of 10 times nonthing shows up. No username at all and also im trying to print out the id of the user but it's also empty.
It seems that it's not getting anything at all from the database when refreshing and sometimes it get's data from the database. Any idea why this might happen?
In this particular case, the problem is that you're working with two different queries; the first query is:
SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users`
Whereas the second one includes a condition:
SELECT * FROM `users` WHERE profile_image='2' LIMIT $offset, 1
^^^^^^^^^^^^^^^^^^^^^^^
Both queries should operate over the same result set.
Its because in your first query you dont have a where, but in the second query you do.
if you have 50 rows and only 15 with profile_image = 2 That will be the reason why most appear as nothing.
Your query becomes LIMIT 30,1 when there are only 15 results for example
Make sure the same where is used in both queries.
Also avoid using mysql_* functions in new code
The solution for my problem was this, BIG thanks to: #Jack
This query will find random row in a mysql table very fast.
$gender_search = $logged_in_user['gender_search'];
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` WHERE profile_image='2' AND gender='$gender_search'");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( "SELECT * FROM `users` WHERE profile_image='2' AND gender='$gender_search' LIMIT $offset, 1 " );
$random_date = mysql_fetch_array($result);
I have now converted this string to PDO if someone needs it.
$statement = $dbConn->prepare("SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` WHERE profile_image=? AND gender=?");
$statement->execute(array('2',$logged_in_user['gender_search']));
$offset_row = $statement->fetch(PDO::FETCH_OBJ);
$offset = $offset_row->offset;
$statement2 = $dbConn->prepare("SELECT * FROM `users` WHERE profile_image=? AND gender=? LIMIT ?, 1");
$statement2->execute(array('2', $logged_in_user['gender_search'], $offset));
$random_date = $statement2->fetch(PDO::FETCH_BOTH);

QL_CALC_FOUND_ROWS pdo?

I'm trying to convert a script from basic sql to pdo. I'm not so good at it, but i have come this far that my pdo returns all the rows in the database (limit 12) i can make 2 statements one without the limit and one with the limit. but in the sql that is originally there, it uses QL_CALC_FOUND_ROWS what this does I think, is that i returns the total rows, and the limit rows, so that the query is faster.
How can i do it with PDO ?
CODE:
<?
// NORMAL SQL
$result = mysql_query('SELECT SQL_CALC_FOUND_ROWS * FROM photos ORDER BY id ASC limit 12');
$row_object = mysql_query('SELECT Found_Rows() AS rowcount');
$row_object = mysql_fetch_object($row_object);
$actual_row_count = $row_object->rowcount;
// PDO
$result = $pdo->prepare('SELECT * FROM photos ORDER BY id ASC limit 12');
$result->execute();
$TOTALrows = $result->rowCount();
?>
EDIT:
Tried some things but this won't work:
$result = $pdo->prepare('SELECT SQL_CALC_FOUND_ROWS * FROM photos ORDER BY id ASC limit 12');
$result->execute();
$resultALL = $pdo->prepare('SELECT Found_Rows() AS rowcount');
$resultALL->execute();
$resultALL->fetch(PDO::FETCH_OBJ);
$actual_row_count = $resultALL->rowcount;
EDIT2: Still no success..
$result = $pdo->query('SELECT SQL_CALC_FOUND_ROWS * FROM photos ORDER BY id ASC limit 12');
$resultALL = $pdo->query('SELECT Found_Rows() AS rowcount');
$resultALL->fetch(PDO::FETCH_OBJ);
$actual_row_count = $resultALL->rowcount;
print_r($actual_row_count);
echo $actual_row_count;
Doesn't echo anything.
Credits also go to Explosion Pills here...
When you're not feeding your query with external input, you don't really have to prepare your statement:
$result = $pdo->query("SELECT SQL_CALC_FOUND_ROWS * FROM photos ORDER BY id ASC LIMIT 12");
This should work!

Select random row in SQL where Status = 0 using php

I wonder... is this possible to select a random row in my DB where only the record that contains field->Status = 0 ? because i only need a row that contains 0 in the field name=Status. if the status contains = 1 , then the row will not belong in the randomization.
my code in the query is
$result = mysql_query( " SELECT * FROM `$haha` ORDER BY RAND() limit 1");<br>
$result = mysql_query( " SELECT * FROM `$haha` ORDER BY RAND() limit 1 Where Status=0");
But it does not work.. i appreciate your replies.. thank you very much!
Try below code:
$result = mysql_query("SELECT * FROM `".$haha."` Where Status=0 ORDER BY RAND() limit 0,1");
Your where clause should be before then the order by clause.
And want to know what is the value of $haha.
You use the wrong syntax. The good one:
$result = mysql_query( " SELECT * FROM `$haha` Where Status=0 ORDER BY RAND() limit 1");

Categories