Fast random row in MySql - php

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

Related

If value from database on user is 0 then execute php code

Hi guys i'm quite new to PHP but I'm currently working on this site and I want it to check if the total_online_time for the user is 0 or less then it should execute the script which will create a room for the user. However after trying with this script the .php page won't load.
http://pastebin.com/XDLhFvtE
<?php
$getStats = mysql_query("SELECT total_online_time FROM `users` WHERE id = '".$_SESSION['user']['id']."'");
if ($getStats > 0)
$getRoomKit = mysql_fetch_assoc(mysql_query("SELECT * FROM room_starterkit ORDER BY RAND() LIMIT 1"));
$getRoom = mysql_fetch_assoc(mysql_query("SELECT * FROM `rooms` WHERE id = '".$randomRoomID['id']."' LIMIT 1"));
$welcomeMessage = "Welcome " . $_SESSION['user']['username'];
mysql_query("INSERT INTO `rooms` (caption,owner_id,description,model_name,wallpaper,floor) VALUES ('".$welcomeMessage."', '".$_SESSION['user']['id']."', 'Welcome to Hablore', '".$getRoomKit['room_Model']."', '".$getRoomKit['room_Wallpaper']."', '".$getRoomKit['room_Floor']."') ");
$theRoomID = mysql_fetch_assoc(mysql_query("SELECT id FROM `rooms` ORDER BY `id` DESC LIMIT 1"));
mysql_query("UPDATE `users` SET `home_room` = '".$theRoomID['id']."' WHERE `id` = '".$_SESSION['user']['id']."'");
$getRoomItems = mysql_query("SELECT * FROM room_itemkits WHERE roomKit = '".$getRoomKit['id']."'");
while($CurItem = mysql_fetch_assoc($getItems)){
mysql_query("INSERT INTO `items` (user_id, room_id, base_item, extra_data, x, y, z, rot, wall_pos) VALUES ('".$_SESSION['user']['id']."','".$lastRoomID['id']."','".$CurItem['base_item']."','".$CurItem['extra_data']."','".$CurItem['x']."','".$CurItem['y']."','".$CurItem['z']."','".$CurItem['rot']."','".$CurItem['wall_pos']."')");
}
}
?>

Update the selected random row PHP

I'm trying to update the selected random row in database here is my php code
$offset_result = mysqli_query($conn, "SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `tbl_combi` WHERE `clear` = 0 ");
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysqli_query($conn, "SELECT * FROM `tbl_combi` LIMIT $offset, 1");
$result_fetch = mysqli_fetch_array($result);
echo $result_fetch[1];
You never perform any update. Here is something you could try (it might need some tuning to fit your need) :
$offset_result = mysqli_query($conn, "SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `tbl_combi` WHERE `clear` = 0 ");
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$updateSql = 'UPDATE tbl_combi SET my_field="my_value" WHERE offset=' . $offset;
mysqli_query($conn, $updateSql);
$result = mysqli_query($conn, "SELECT * FROM `tbl_combi` LIMIT $offset, 1");
$result_fetch = mysqli_fetch_array($result);
echo $result_fetch[1];

How to use php variables in mysql query while php variable contains mysql query?

How can I implement something like this in mysql?
$query1 = "SELECT id FROM table WHERE username = 'John'";
$query2 = "SELECT id FROM table WHERE username= 'Parsa'";
$query = "SELECT * FROM table WHERE id BETWEEN $query1 AND $query2";
$result = mysql_query($query) or die('Query faild'.mysql_error());
$myrecord = mysql_fetch_assoc($result);
Try this
$query1 ="SELECT GROUP_CONCAT(id) FROM table WHERE firstname in('John','Parsa')";
$query = "SELECT * FROM table WHERE id IN ($query1)";
you have two identical queries , you could just have one . and use IN , not BETWEEN.
You can put those 3 queries in to one query:
$query = "SELECT * FROM table WHERE id
BETWEEN
( SELECT id FROM table WHERE firstname = 'John' GROUP BY id )
AND
( SELECT id FROM table WHERE firstname = 'Parsa' GROUP BY id )
";
although your query doesn't mean anything; you need "()" for subqueries to work.
$query1 = "(SELECT id FROM table WHERE username = 'John')";
$query2 = "(SELECT id FROM table WHERE username= 'Parsa')";
$query = "SELECT * FROM table WHERE id BETWEEN $query1 AND $query2";
u can use a subselection:
SELECT * FROM table WHERE id BETWEEN ($query1) AND ($query2)
But be careful: The Subselection result must be an Integer.

Pass column value from Select query to another query for insertion in PHP

I was thinking of accomplishing the following as a PHP multi_query. But I'm trying to figure out how to pass the column value from the select query to the insert and update queries.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$query .= "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query .= "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
Problem is, I'm not sure how to pass the link_id value to the other queries. So I'm thinking I might have to rearrange the queries into one, but again, I'm just not sure how to pull that off.
Anyone got any suggestions?
You need to execute select query 1st then use its output to execute 2nd & 3rd query.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$query2 = "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query3 = "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
mysql_query($query2);
mysql_query($query3);
}

How to fetch a random record from SQLite database?

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.

Categories