编辑:感谢您更正格式...没有注意到错误
我已经完成了这个基本报价生成器作为第一个项目,但是注意到它经常在刷新时显示相同的报价。当然,目前只有五个,但是当我填满数据库时,可能这个问题仍然很明显。我目前正在学习更高级的JQuery AJAX - 但我才开始。据我所知,这不是一个重复的问题。重新加载时显示数据库查询。谢谢! 这是代码:
connect.php:
<?php
$connection = new mysqli('localhost', 'root', '', 'random_quotes');
if ($connection->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ')'
. $mysqli->connect_error);
}
?>
的functions.php:
<?php
require ('connect.php');
$query = "SELECT id, quote, author FROM quotes ORDER BY RAND() LIMIT 1";
$getQuote = $connection->query($query);
?>
HTML:
<!doctype html>
<html lang="en">
<?php
require ('includes/connect.php');
require ('includes/functions.php');
?>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Candal' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container-fluid text-center">
<h1>Random Quote Generator</h1>
<p>Some of my favourite all around quotes!</p>
<br/>
<button class="btn btn-default" onclick="newQuote()" type="submit">New Quote
</button>
<div class="quote_wrap text-center">
<span class="quote">
<?php
while($row = $getQuote->fetch_assoc()){
$stringID = $row['id'];
$stringQuote = $row['quote'];
$stringAuthor = $row['author'];
echo $stringQuote;
}
?>
</span>
</br>
<div class="author text-center"><?php echo $stringAuthor?></div>
<div class="quoteid" id="<?php echo $stringID?>"></div>
</div>
</div>
<script src="https: /ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
function newQuote() {
location.reload();}
</script>
</body>
</html>
答案 0 :(得分:0)
生成随机数,然后按该ID访问引号。可能会更好..
$query = "SELECT COUNT(*) as noQuotes FROM quotes ";
$result = $connection->query($query);
$row = $result->fetch_assoc();
$noQuotes = $row["noQuotes"];
srand(time());
//echo(rand(1,$noQuotes));
$randNo = rand(1,$noQuotes);
$query = "SELECT id, quote, author FROM quotes WHERE id = $randNo ";
$getQuote = $connection->query($query);