Vinay
Vinay

Reputation: 57

Delay between each mysql query in php

This is my code for getting the mysql table content

I am getting whole data at once.

I want to put a time delay in each of the query.

$host= "localhost";
$user= "xxxxx";
$pass= "xxxx";
$db="xxxxx";

$connect= mysql_connect($host,$user,$pass);
if (!$connect)die ("Cannot connect!");
mysql_select_db($db, $connect);

$result = mysql_query("
    SELECT
        *
    FROM
        url
");

if($result){
    while($row = mysql_fetch_array($result, MYSQL_ASSOC)){

$url = $row['urlss'];
echo '<li>'.$url.'</li>';
}
}

The result output is

row1
row2
row3
row4

I want to get output In below manner

row1
//wait 5 sec
row2
//wait 5 sec
row3
//wait 5 sec
row4
//wait 5 sec

Thanks

Upvotes: 0

Views: 2748

Answers (4)

Nitin
Nitin

Reputation: 916

You could use

foreach ($row as $text) {
    //output text, sleep 5 seconds 
    echo $text; 
    ob_flush(); 
    flush(); 
    sleep(5); 

}

But javascript could be a better option in this case as you send all data to the client first and use javascript interval to iterate a $row each 5 seconds.

echo '<script type="text/javascript">
    var data = ' . json_encode($rows) . '; 
    var output = document.getElementById("output-id");
    var i = 0;
    var no_rows = data.length;
    var interval = setInterval(function() {
       output.appendChild(document.createTextNode(data[i].columnName));
         i++;
         if (i >= no_rows) {
             clearInterval(interval);
         }
    }, 5000);
</script> ';

Upvotes: 0

Bogdan Bocioaca
Bogdan Bocioaca

Reputation: 36

if i'm not mistaking and i understood correctly you need to use ob_flush() http://php.net/manual/en/function.ob-flush.php

Upvotes: 0

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

Use client side script jquery/javascript to achive it.

PHP code:

<?php 
// code for DB connection and query

echo "<ul id='list-results'>";
if($result){
 while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    $url = $row['urlss'];
    // display none 
    echo '<li style="display:none">'.$url.'</li>';
 }
}
echo "</ul>";
?>

Jquery:

// include jquery
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  // read all list tlements
 $( "#list-results li" ).each(function( index ) {
    // fade in each li
    $(this).delay(5000*index).fadeIn();
    });
});
</script>

Upvotes: 3

Orion
Orion

Reputation: 125

If you want a delay, then you could try PHP's sleep function

$host= "localhost";
$user= "xxxxx";
$pass= "xxxx";
$db="xxxxx";

$connect= mysql_connect($host,$user,$pass);
if(!$connect) die ("Cannot connect!");
mysql_select_db($db, $connect);

$result = mysql_query("SELECT * FROM url");

if($result){
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        $url = $row['urlss'];
        echo '<li>'.$url.'</li>';
        sleep(5); //sleep for 5 seconds
    }
}

Upvotes: 0

Related Questions