Matt Brand
Matt Brand

Reputation: 346

How to dynamically display MySQL data using jQuery and PHP?

I have a PHP page that lists a bunch of words that it grabs from a MySQL database table. It displays the words in different sizes based on a count in the table:

<?php
 $selectStr = "select * from test";

 if ($results = MySQL($dbName, $selectStr))
 {
  $rowCount = MySQL_NUMROWS($results);
 }

 $i = 0;
 while ($i < $rowCount)
 {
  echo '<div style="float: left; font-size:' . (MySQL_RESULT($results,$i,'count') * 5) . 'px;">' . MySQL_RESULT($results,$i,'word') . '</div>';
  $i++;
 }
?>

The trick is that I want the content to display dynamically. So if a user is sitting on the page, and one of the word counts goes up, I want the word to change size without the user refreshing the page.

I am a novice with jQuery. I have used it a bit before, but only using examples. Can someone steer me in a good direction to have my page dynamically change the content without refreshing?

Upvotes: 3

Views: 5610

Answers (2)

Jurgo
Jurgo

Reputation: 905

It calls the file rowfunctie.php every 30000ms and fills the topbar diff with with the result of the getRows function.

<div id="center-rows">
  <div id="links">Nu&nbsp;</div>
  <div id="rows">
    <div id="topbar"></div>
  </div>

  <div id="rechts">&nbsp;aantal rijen</div>
</div>

<script type="text/javascript">
function doRequest() {
  jQuery("#topbar").fadeOut('slow', function() {
    jQuery.ajax({
      type: "GET",
      url: "rowfunctie.php",
      cache: false,
      success: function(html){
        jQuery("#topbar").html(html);
        jQuery("#topbar").fadeIn('slow',function() {
        setTimeout('doRequest()',30000);
      });
   }
 });
 });
}
doRequest();
</script>

rowfunctie.php should look like this beneath:

<?php 
 $selectStr = "select * from test";

 if ($results = MySQL($dbName, $selectStr))
 {
  $rowCount = MySQL_NUMROWS($results);
 }

 $i = 0;
 while ($i < $rowCount)
 {
  echo '<div style="float: left; font-size:' . (MySQL_RESULT($results,$i,'count') * 5) . 'px;">' . MySQL_RESULT($results,$i,'word') . '</div>';
  $i++;
 }
?>

Upvotes: 0

Wearybands
Wearybands

Reputation: 2455

You can auto refresh your page body like this ... give body id='body'

 <html>
 <head>
    <script type="text/javascript">
       var auto_refresh = setInterval(
         function ()
         {
          $('#body').load('wordscount.php').fadeIn("slow");
         }, 10000); // refresh every 10000 milliseconds
    </script>
 </head>
 <body>
     <div id='content'></div>
 </body>

Dont forget to include jquery inside your head tag

Upvotes: 3

Related Questions