Random data returned from mysql database one after another?
I have a database of facts and I want to display one of these facts at random for say 10 seconds then for it to choose another fact and display it for 10 seconds and so on.
Currently I can get it to display a random fact fine using the code below however I am a bit confused about 开发者_如何学Chow to show this for 10 seconds and then display a different fact. Any help or advice would be brilliant? Thanks.
<?php
$linkid = $_GET['linkID'];
$query = "SELECT *
FROM facts
ORDER BY RAND()
LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$factxt = $row ['factxt'];
echo $factxt;
}
?>
Hi, ok I tried both of the ways suggested below, using ajax and jquery but both are returning the same error from the database:
Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in getfact.php on line 4
This is line 4 of getfact.php,$query = "SELECT * FROM facts order by rand() limit 1";
$result = mysql_query($query);
is there something that I am doing wrong?
You can use Ajax with help of jQuery library.
Sample code:
setInterval(retrieveFact, 10000); // call retrieveFact() every 10 seconds
function retrieveFact() {
// make an asynchronous call to getfact.php
$.post('/getfact.php', function(data) {
// when it returns, set the content of div with id=#factbox
$('#factbox').html(data);
});
});
Here, getfact.php
would be the code you pasted on the question.
And in your html somewhere place the element that will receive the text:
<div id="factbox"></div>
More references:
- How to setup jQuery in your pages
- Documentation for post()
- Documentation for jQuery
First you must to include the jQuery library, then use this example code.
somefile.php/html:
<script type="text/javascript" src="jquery.min.js"></script>
<script>
function getRand() {
$.ajax({
url: "getFact.php",
success: function(response) {
$("#random").html(response).hide().fadeIn("slow");
}
});
};
setInterval("getRand()", 10000);
</script>
<div id="random"></div>
getFact.php:
<?php
$linkid = $_GET['linkID'];
$query = "SELECT * FROM facts order by rand() limit 1";
$result = mysql_query($query);
$factxt= $row ['factxt'];
echo $factxt;
?>
When the LIMIT is 1, you don't need to put information into loop.
You can use ajax for this with an interval that loads in some data via ajax/getJSON or load this page in an iframe and add an automated refresh every 10 seconds (meta refresh).
精彩评论