Display new database row every x seconds PHP

Hi there,

I think my problem is quite basic… I need to display a new testimonial text from the DB, every 5 seconds, for example.

Below is my code, but as expected, what it does, is show all rows of my ‘testimonials’ table. Could you give me some ideas?

<?php
	include 'connect.php';
									 
	$sql = $dbh->prepare("SELECT * from testimonials");
	$sql->execute();
					
	foreach ($sql->fetchAll() as $ligne) {
	$testimonial = $ligne["testimonial"];
	$testimonial_author = $ligne["testimonial_author"];
												
	echo '<p>'.$testimonial.'</p>';
	echo '<p>'.$testimonial_author.'</p>'; 
						
	}
?>

Many thanks!

To do this purely in php would require a page refresh every 5 seconds, which would not be good.
So I think you would want to use some client-side scripting too.
There are two ways I can think of how it may work. One would be that the client side script makes a request every 5 seconds to get the server side to pull a new row from the db. But it may be more efficient for the server side to pull all, or just enough rows initially, which are passed to the client side, which will dish them out one at a time, every 5 seconds.
This is not something I have tried, so may be wrong about this, but going with the second method, as far as the php (server-side) is concerned, I would probably start with processing all the required rows into an array which could then be output into the page as json data to be used by the client side.
How you then proceed with the client side script, would probably be best asked in the javascript forum.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.