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.