The website I am working on provides a service, where only members can get full access to the content. I am trying to create a ‘sample’ on the homepage that fetches NEW mysql data (that is normally available for members only) every day and provides ALL users with a ‘free sample’ of what the site has to offer.
The database contains over one thousand entries and I would like to find a way to fetch new mysql data from the db every day.
Assuming my database looks like this:
id cars
1 honda
2 volvo
3 ford
4 audi
I would like the ‘car of the day’ to be ‘honda’ for 24 hours, then ‘ford’ for 24 hours, then ‘audi’ for 24 hours, etc…
this is what I have so far:
<?php
//Create mysql connect variable
$conn = mysql_connect('server', 'username', 'password');
//kill connection if error occurs
if(!$conn){
die('Error: Unable to connect. <br/>' . mysql_error());
}
//connect to mysql database
mysql_select_db("masdswe9", $conn);
$results = mysql_query("SELECT * FROM cars");
$name_array = Array();
while($row = mysql_fetch_array($results)){
$name_array[] = $row['name'];
}
shuffle($name_array);
/* I would like for this to fetch NEW SQL data every 24 hours,
since I am shuffling names above, slot 0 will be different once I
come up with a way to fetch new mysql data every 24 hours */
echo $name_array[0];
?>
I would create a DB table called
CarOfTheDaythat you can select from (it will just have the ID of the car in theCarstable). Either that or you can have a columncarOfTheDay, or change the order of the cars, but I think those are a bit more intrusive.Create a cron that runs once a day ans writes a random car to
CarOfTheDay. Then, you can do what you are doing above, but you don’t have to worry about timing and you will only select one car:The
LIMITshould not be necessary if you stick to oneCarOfTheDay.By the way, use
PDOormysqlirather thanmysql_*. Only select columns you need (don’t useSELECT *in production code) .. and only select rows you need (you can randomize in the query).