Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End PHP Daily Quote Script

  • This topic is empty.
Viewing 9 posts - 1 through 9 (of 9 total)
  • Author
    Posts
  • #31158
    Adman
    Participant

    Good evening all!

    So I’m working on a website for my buddy and I am not familiar with PHP, however I did find a script that would allow me to change a quote every 24 hours. The part I don’t like is it uses cookies and not server information like each day, it changes based on the server day. Here is the script I’m using now.

    
    $numDB = 1;
    /*
    The variable $numDB informs the script how many quote databases to pull from.
    */
    $dbFileName = array("facts.db");
    /*
    The variable $dbFileName is an array of the paths to the quote databases. The example above indicates that the database files are in the same directory as the script. If you put them in a different directory, say quotes/, then this variable would look like:
    $dbFileName = array("quotes/political.db","quotes/religious.db");
    */
    $quoteType = 2;
    /*
    The variable $quoteType determines the type of quote generation.
    quoteType = 0 displays a new random quote each time the page is loaded.
    quoteType = 1 displays a new random quote every 60 minutes.
    quoteType = 2 displays a new random quote every 24 hours.
    quoteType = 3 displays a new random quote once every 7 days.
    Settings 1, 2 & 3 are handled by storing a cookie. Use the included "del_cookie.php" script to delete the cookie while you are testing the script.
    */
    if ($numDB == 1){
    $filename = $dbFileName[0];
    }else{
    $ranDB = rand(1, $numDB);
    $filename = $dbFileName[$ranDB-1];
    }
    /*
    This conditional Statement if ($numDB == 1){.... is picking the database from which to pull the quotes. If the variable $numDB is set to 1 it pulls the first db in the array. You will notice that $dbFileName is set to 0. This is because most languages consider 0 to be the first number when counting.
    */
    $lines = file($filename);
    $numQuotes = count ($lines);

    if ($quoteType == 0){
    $ranNum = rand(1, $numQuotes);
    } elseif ($quoteType == 1){
    if (isset($_COOKIE)) {
    $ranNum = $_COOKIE;
    } else {
    $ranNum = rand(1, $numQuotes);
    setcookie("quoteNum", $ranNum, time()+60*60);// One Hour
    }
    }elseif ($quoteType == 2){
    if (isset($_COOKIE)) {
    $ranNum = $_COOKIE;
    } else {
    $ranNum = rand(1, $numQuotes);
    setcookie("quoteNum", $ranNum, time()+60*60*24); //Twenty-four Hours
    }
    }elseif ($quoteType == 3){
    if (isset($_COOKIE)) {
    $ranNum = $_COOKIE;
    } else {
    $ranNum = rand(1, $numQuotes);
    setcookie("quoteNum", $ranNum, time()+60*60*24*7); // Seven Days
    }
    }
    /*
    This conditional Statement if ($quoteType == 0){.... is determining the interval at which you want the quotes displayed. This feature uses the Set Cookie function. Which places a cookie in the users browser.
    */
    $line = $lines[$ranNum-1];
    $element = explode("::",$line);
    $theQuote = $element[0];
    $theRef = $element[1];
    $theLink = $element[2];
    include ('func.php'); // this references the HTML that will be output to the browser.
    $output = outputLine($theQuote, $theRef, $theLink);
    // $output = outputTable($theQuote, $theRef, $theLink);
    echo $output;
    ?>

    Then in the HTML I call this $output. Is the code complicating things or inefficient? I considered JS but if someone has it disabled then it won’t ever change the quote. However if someone disables cookies then I’m assuming it will do the same. Anyone care to give me some pointers for this? Thank you!

    #67205
    Bob
    Member

    Exactly what are you trying to accomplish? The way I see it, you’re trying to output a different string of text everyday? Why use such a complex code for that? I made this quickly, haven’t tested it but it should work:

    
    
    $day = date("l");

    switch($day) {
    case "Monday":
    echo "This is the daily quote for monday!";
    break;
    case "Tuesday":
    echo "This is the daily quote for tuesday!";
    break;
    case "Wednesday":
    echo "This is the daily quote for wednesday!";
    break;
    case "Thursday":
    echo "This is the daily quote for thursday!";
    break;
    case "Friday":
    echo "This is the daily quote for friday!";
    break;
    case "Saturday":
    echo "This is the daily quote for saturday!";
    break;
    case "Sunday":
    echo "This is the daily quote for sunday!";
    break;
    }

    ?>

    I don’t know if thats what you’re looking for, but if you do its a bit simpler than your code :)

    Edit: if one of the mods read this, could you tell me why sometimes the forums show code with code highlighting, and sometimes it doesn’t?

    #67083
    gno
    Member

    Bob is spot on. There’s no need for such complicated code.

    Is it really necessary to make it change each day? If its really important, to have it change each day, I imagine that it would require something else than a random choice too.

    So, if its not crucial to have it change every 24 hours, then you could just get a random quote each time. Fx. by getting all the id’s of the quotes from your database, then selecting a random number from the range lowest-id -> max-id and then getting the quote related to that id.

    Or, you could add a column to your database, containing a date. Your script should then first look for a quote with the current date- if there is no result (the first request that day) it should select a random quote, and then save the current day in the new column. You could make it only choose from quotes which have not been shown for a week if you desire to.

    Both possibilities are a lot simpler than the one you suggest, and a little more complicated than the switch-case solution Bob suggested. Choose whatever makes the most sense to use in your project.

    #67072
    gno
    Member

    I’d say, that you should use a sql database for it – either SQLite or MySQL. MySQL is a bit overkill, but it is easier to work with for newcomers (at least, that is my experience).

    The text file you are using is not a relational database, and while you could accomplish the same thing with text files, it would be a waste of time and resources.

    I’ll give you a little example. This uses mysql and php.

    Bear with me if it fails. I have not tested it – I just wrote it off the top of my head. :-)

    The mysql table:


    CREATE TABLE `quotes` (
    `id` int(3) not null auto_increment,
    `quote` text,
    `person` text,
    `lastused` date default '2010-10-10',
    PRIMARY KEY (`id`)
    )

    The PHP code:


    // Connect to Mysql Database

    // Checking if theres already selected a quote for today
    $quoteQuery = mysql_query('SELECT quote,person FROM quotes WHERE lastused = CURDATE()');

    // If not:
    if (mysql_num_rows($quoteQuery) != 1) {
    // Get all quotes from db which havent been used in the last 7 days
    $idQuery = mysql_query('SELECT id FROM quotes WHERE DATEDIFF(CURDATE(),lastused) > 7');
    // Getting a numerated array only
    $ids = mysql_fetch_array($idQuery, MYSQL_NUM);
    // Count the number of elements in that array
    $idCount = count($ids);
    // Getting a random number - $ids[$id] will now contain our random number.
    $id = rand(0,$idCount);

    // Update that row
    mysql_query('UPDATE quotes SET lastused = CURDATE() WHERE id = '.$ids[$id]);

    // Getting the newly selected daily quote
    $quoteQuery = mysql_query('SELECT quote,person FROM quotes WHERE lastused = CURDATE()');
    }

    $row = mysql_fetch_row($quoteQuery);
    ?>




    #67000
    gno
    Member

    A little note, this script wont work if there is less than the number specified in the $idsQuery. In this case the minimum number of quotes in the database for this script to work would be 8. And then, there would be nothing random about their selection, as after they have all been shown once, there will only be one to choose each time.

    To make this script a little smarter, you could make the number of days that a quote cannot reappear in totalNumberOfQuotes/4 – so if there’s 8 quotes, one quote would not appear with less than 2 days since last time.

    I would not do this dynamic limit thing myself, but it could potentially safe the day, if your friend chooses to delete most of his quotes one day, and gets below the magical limit.

    #67002
    gno
    Member

    I hope you can use it.

    Please let me know if you get errors – if you cant solve em, I’ll help you out – if you can, other people visiting this thread will not be stuck with a half-working script :-)

    #66341
    gno
    Member

    Does the lack of followup question mean that I have actually produced working code from this forum box? :D

    #66343
    gno
    Member

    By reviewing my code I found at least one error – not a fatal one, but still.

    The line $idCount = count($ids); should be $idCount = count($ids) -1; as arrays in php are 0-indexed. Meaning that the first key is 0, not 1. The variable declaration of $id reflects that, as it selects a random value from 0 to the number of keys. It should however be the number of keys – 1. Which is what the change of $idCount will do ;-)

    #66113
    gno
    Member

    I’m by no means a genius! But I’m glad it worked.

    What works the magic in our little script is not PHP. What I do with PHP is just the usual array handling and mysql interaction. It is the SQL queries where the interesting stuff happens.

    As for references to resources about learning PHP – I have no other ideas than pointing you to http://www.php.net. PHP has the best manual that I have ever seen for any programming language. But that wont help you as much if you have not understood the basics yet. By basics I mean the different constructions and concepts that PHP is build upon.

    Back when I started (and that is just short of 10 years ago- not that it takes that long to learn – a dedicated person could out-do me, in PHP, in a matter of months) I learned the language from a combination of a series of articles in danish and some messing around on a danish PHP channel on IRC (#php.dk on QuakeNet for anyone interested – I have no idea if it is still around tho).

    In 2003 I borrowed the book “Beginning PHP4” from Wrox (published in 2000 I think) on the local library. That book gave me a solid foundation for learning PHP and I think that it helped me alot. As a side note – I was 13 at the time and in the 7th grade of the danish elementary school. I have had english lessons for like 2 and a half year at the time – my teacher did not believe me when I told her that I just finished reading a 800 pages english book about programming webpages… I think that I learned the english language mainly due to playstation games and that book ;-)

    Reading that book now would be stupid, as a new version of PHP has come out since then. But I imagine that that sort of books are still around. There is no easy way of learning it – it takes time and dedication. But do not just sit there and wait for it. Write a lot of buggy code, fix it – rinse repeat. Everytime you write new code it will be less buggy than before.

    I still make bugs – even in the very example I made for you ;-)

    Reference to the book: http://www.wrox.com/WileyCDA/WroxTitle/Beginning-PHP4.productCd-0764543644.html

Viewing 9 posts - 1 through 9 (of 9 total)
  • The forum ‘Back End’ is closed to new topics and replies.