-1

I'm still new to PHP and MySQL. I'm currently working on a random quote generator website. When a user visits for the first time or refreshes the page, the PHP code fetches a random row from the MySQL table and echos the results.

If a user likes a particular quote, I want him/her to be able to bookmark the page the quote is contained in. I believe this requires a unique URL for each random code that is generated. I can't figure out how to do this with the code I currently have and would like anyone's help.

This is my table so far:

+----+-----------+-----------+
| id | quote     | source    |
+----+-----------+-----------+
|  1 | hello     | test1     |
|  2 | world     | test2     |
|  3 | random    | test3     |
+----+-----------+-----------+

This is my code so far:

<?php

require('connection.php');

// Last query result stored in sessions superglobal to avoid immediately repeating a random quote
session_start(); 

if (empty($_SESSION['lastresult'])) {
    $_SESSION['lastresult'] = null;
}

$query = "SELECT * FROM `test` WHERE `id` != '%s' ORDER BY RAND() LIMIT 1";
$query =  sprintf($query, mysql_real_escape_string($_SESSION['lastresult']));
$result = mysqli_query($dbc, $query) or die(mysql_error());

if (mysqli_num_rows($result) == 1) {
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $_SESSION['lastresult'] = $row['id'];
        echo '<p>' . $row['quote'] . '</p>' . '<p>' . $row['source'] . '</p>';
    } 
} else {
    echo '<p>Sorry, there was an error. Please try again by refreshing the page or clicking the query button.</p>';
}

?>   

Any other code advice would also be appreciated.

edubba
  • 1,347
  • 2
  • 10
  • 8

1 Answers1

0

There are three ways that spring to mind.

All require you to implement a version if the page that takes a quote id, similar to the one @DanGoodspeed suggests in his comment against your question.

  1. Add a link from you existing page to the new id driven page with a label 'bookmark this page to return'. Not ideal, but very simple.
  2. Add some JavaScript in your existing page to update the URL after loading to include the id, therefore making it appear as if it was the other. See this answer Modify the URL without reloading the page for details.
  3. Instead of using the page you have now, generate a new page (using much of what you have already written) that returns a location redirect header with a URL that has a random id in it.
Community
  • 1
  • 1
Rob Baillie
  • 3,436
  • 2
  • 20
  • 34