I have a simple query that displays random results, however I'd like to be able to keep those same results for a 24 hour period per visitor so it doesn't randomize on every page refresh. Here's the query:
<?php
$rs1= mysql_query("
SELECT * FROM Table_1
ORDER BY RAND()
LIMIT 4
");
while ($row1= mysql_fetch_array($rs1)) { ?>
I gather I'll need to use the date somehow. I did figure out how to get a random number to show for 24 hours:
<?php
date_default_timezone_set('America/Los_Angeles');
mt_srand(date('Ymd'));
$number = mt_rand(50, 5000);
mt_srand(); //reset for other calls
echo $number;
?>
But I'm not sure how to make that work with my original query. Any ideas? Or should I be creating a cookie rather than trying to do it with only php? How would I make a cookie work with it?
This is a bit CPU intensive if you have to calculate over lot of rows, but do not uses cookies nor any special data to keep selection.
select * from table order by md5(concat(id,curdate())) limit 4
Will show same order on every query on the same day. If want to be diferent based on the user doing the query but still the same on the day, you can add his id to the concat too.
select * from table order by md5(concat(id,userID,curdate())) limit 4
Should be say, that results are no more random and can be predicted by someone that takes the job. You can add a seed too, to mitigate some way this effect.
Pass the date seed that you are using into the query. MySQL's rand() function also takes a seed which would make your random results the same.
http://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_rand
Here is an example using the mysqli extension since mysql is deprecated.
<?php
date_default_timezone_set('America/Los_Angeles');
mt_srand(date('Ymd'));
$number = mt_rand(50, 5000);
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT * FROM Table_1 ORDER BY RAND(?) LIMIT 4");
$stmt->bind_param('i', $number);
$stmt->execute();
You could also just do it all in the query
SELECT * FROM Table_1 ORDER BY RAND(CAST(CONCAT(YEAR(), MONTH(), DAY()) AS UNSIGNED)) LIMIT 4
Or whatever seed you want to get from the date.
Save/cache the result to a file (using serialize()) and use the contents of this file to generate your page. Then refresh this file every 24 hours as needed.
Related
I have a history table with 3700000+ entries. I am using server-side processing in the datatable to initially display 25 records. It is taking lots of time to initially load the datatable even though the query fetches only 25 records.
I am using MySQL database. Now I want to limit the total number of entries from which the data should be processed. I want only past 15 days entries to be considered.
Is there a way by which I can load the table quickly?
There are a number of ways you can limit how much data you get back from a SQL Query.
Using WHERE will allow you to only select entries after a certain date.
$sql = "SELECT * FROM history WHERE date > ".strtotime("-15 days");
The above query assumes that in your history database you have a date that is a unix based timestamp. Another way that you could limit the amount of data that is returned is by using the LIMIT function.
$sql = "SELECT * FROM history ORDER BY id DESC LIMIT 15";
This query assumes that you only have one entry per day, and will limit it to only 15 entries to be displayed.
Along with this, if your history table has a lot of data that doesn't need to be used, then you can only select the columns that you need, doing something like this:
$sql = "SELECT id, time, name FROM history";
SELECT * FROM $table_name WHERE created_date>= DATE(NOW() - INTERVAL 15 DAY)
I have a page that shows posts stored in a mysql database. When the post is created the user can select how long they want the post to be visible for and I'm trying to figure how to only show posts for a determined duration. Here is some of my code (that hopefully shows the logic I'm trying).
//Query database
$sql = <<<SQL
SELECT *
FROM `posts`
SQL;
if(!$result = $db_connection->query($sql)){
die('There was an error running the query [' . $db_connection->error . ']');
}
while($row = $result->fetch_assoc()){
//The date the post was made
$date_of_post = $row['date_of_post'];
//The duration of the post in days eg 7.
$duration = $row['duration'];
//Attempting to add duration to date
$newdate = strtotime($duration, $date_of_post);
//Only show posts that are still valid, eg date + duration is less than today's date
if($newdate > now()){
echo '<h2>Post Title</h2>';
echo '<p>Date of Posted:'.$date.'</p>';
}
}
You can use a where clause and a date_add function to apply this filter directly in your SQL query. Simply add the duration days to the date_of_post value, and compare it against NOW().
Note that because you're storing your duration value as a varchar instead of an int, you'll need to convert the duration value to a signed int.
Here is an example, with the date_add expanded out to make it clearer to understand what is happening.
select
*
from
posts
where
date_add
(
date_of_post,
INTERVAL convert(duration, SIGNED INT) DAY
) > NOW()
As a side note, you should always try to filter your data in your query, and not in your PHP script. Don't just select your entire table into your script - let SQL do as much work as possible. The RDBMS is far more efficient than PHP, and you'll save a lot on overhead (eg amount of data sent over the network, and how much RAM has to be used to store the results for PHP to work with, etc).
So I have this php code:
"SELECT * FROM thread_db ORDER BY id DESC LIMIT 3";
This echos me later the last 3 rows of my mysql database. I somehow need it to get sorted by time so I get the 3 latest entries by time (closest to current date).
Try this
"SELECT * FROM thread_db ORDER BY your_time_field DESC LIMIT 3";
Replace your_time_field with the exact name of your time column in the query
Basically I have a website where user vote on projects posted by users or "Support" everytime a user clicks the support button, it goes into a table and stores 3 things, a normal auto increment identifier, the user_id that 'supported' it and the project id they supported. Now everyday we want to display 'Top projects' on the homepage. This will my guess be done with a php script and a cron job. I can't really think of how to query the database properly to determine X amount of top projects. (Most likely 5 or 10) Iv'e thought about this for a while, but I can't think of an answer. Any ideas/answers help alot! Thanks.
Well, your going to have to add a time stamp of one sort or another to that database. So you can query by the day from midnight to 11:59p. I'd say datetime format ie: YYYY-MM-DD HH:MM:SS (its in 24 hour format)
From that if handled correctly you could do something like
<?php
$todayMidnight = date('Y-m-d'). ' 00:00:00';
$todayLastMin = date('Y-m-d'). ' 23:59:59';
$result = mysql_query("select * from the_table where the_Time BETWEEN $todayMidnight AND $todayLastMin LIMIT 10 order by the_count");
?>
Suppose, you have an SQL database table called votesTable with a field numberOfVotes.
Without a cron-job or such, you might run this MySQL-query
SELECT *
FROM votesTable
ORDER BY votesTable.numberOfVotes DESC
LIMIT 10
to retrieve the to top 10 vote entries.
This YouTube video PHP Tutorial: Simple Rating / Voting System [part 01] may help (tutorial author's page).
I owns a website which is doing lots of searches per day. these search results are stored in my MySQL databse. what I want is I want retrieve today's top searches from MySQL limit to 20 and display in my website. how do I do this with PHP & MySQL??
Thanks
Mathew
You will need to do something looked like this:
$today = date("F j, Y"); // NOTICE, you have to format your date like you have # database field
$q = " SELECT search_string_field, count(search_string_field) as count
FROM search_results_table
WHERE search_date_field = '$today'
ORDER BY count DESC
GROUP BY search_string_field
LIMIT 20";
$results = mysql_query($q);
and fetch the results after executing query
You'll need to store the time for each search. With that you can query the database (using date ranges and limit) for the popular searches within a time period or you can do it with PHP.
What metric do you have for storing searches. Do you store every search term, or update a number if the term was used more than once?
If you have a number of terms searched
$query = 'SELECT * FROM searches ORDER BY searched DESC LIMIT 20';
But I think you need to give more info... what does your table look like?