1

I am looking for a starter code that searches a MySQL table and and displays 3 columns of data and the picture (stored path) separated by individual tables:

-------------------------------
IMAGE: Player: Andre Dawson 
       Brand: Topps 
       Year: 1989

added:1 minute ago
------------------------------- 
IMAGE: Player: Jose Conseco 
       Brand: 
       Score Year: 1991

added: 10 seconds ago
-------------------------------

I would need this to search for new entries every 30 seconds. Any help is appreciated.

PHP Code:

<?php
  $link = mysqli_connect("localhost","username","password","dbname") or die("Error " . mysqli_error($link));     
  $query = "insert into bbcardindo (player,brand,year) where visiblecards="y";
  mysqli_query($link, $query);
  $lastid = mysqli_insert_id($link);
  $query2 = "insert into newfeed ((player,brand,year, imagenanme))";
  mysqli_query($link,$query2);
  mysqli_close($link); 
  print_r($query2);
?>

Database:

 CREATE TABLE `bbcardindo` (
 `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
 `player` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
 `brand` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
 `year` year(4) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Database Records:

+----------------------------------+
| id | player       | brand | year | 
| 1  | jose conseco | Topps | 1989 |
| 2  | andre dawson | score | 1992 |
+----------------------------------+
AD7six
  • 63,116
  • 12
  • 91
  • 123
Michael E
  • 11
  • 4
  • Where are you looking? – user2182349 Aug 24 '15 at 00:40
  • I am super new to PHP what do you mean specifically? – Michael E Aug 24 '15 at 00:44
  • 1
    What have you tried so far? shoe us your code? – mdamia Aug 24 '15 at 00:45
  • Let me grab it...super embarrassing – Michael E Aug 24 '15 at 00:46
  • Sounds possible, Welcome to SO :) – Craig van Tonder Aug 24 '15 at 00:55
  • Thanks...I have been reading the threads...these people are damn smart...I can't figure out how to post it to my comment :( – Michael E Aug 24 '15 at 00:58
  • Under your question where the tags are, there is share | edit | flag. Click edit and add your code so then people might try to help. It's hard to understand what you are working with or what you are trying / have tried without it. – Craig van Tonder Aug 24 '15 at 00:59
  • Thanks I need to get a hold of SO too...I think my stuff is visible – Michael E Aug 24 '15 at 01:00
  • Do you have a database set up, if yes can you do `SHOW CREATE TABLE bbcardindo` and then edit in that output? Can you do the same for `newfeed`? – Craig van Tonder Aug 24 '15 at 01:06
  • I am going to attempt to post what I have...I just have a tester db so far... – Michael E Aug 24 '15 at 01:11
  • Not the entire database, just the structure of the tables that you have mentioned within your code. – Craig van Tonder Aug 24 '15 at 01:13
  • Columns: id int(11) PK player varchar(45) brand varchar(45) year varchar(45) – Michael E Aug 24 '15 at 01:18
  • I don't have anything for the news feed set up...still trying to get my bearings on how that would be – Michael E Aug 24 '15 at 01:19
  • I fear that this might be a bit over your level of understanding as is. You should actually take a step back and do a bit more research, maybe buy a book and read it :) What you essentially want to do, is poll the database in realtime to retrieve said information. You cannot really do that PHP but you can however accomplish this with Javascript/jQuery and AJAX. See here: http://stackoverflow.com/questions/4200515/how-do-i-do-realtime-database-polling-in-mysql-php – Craig van Tonder Aug 24 '15 at 01:46
  • Btw, now that you have a hang of posting questions and providing all of the required information. Why not remove this question, reformat the content (after accepting my edit) and reposting it as a new question being more accurate in terms of the exact issue that are you facing with this. You are correct in saying that there are smart people on SO but they will seldom help unless you make a good effort on your end too :) – Craig van Tonder Aug 24 '15 at 01:47
  • Sitepoint Premium just launched a new course about learning Javascript... In my mind that would be your best start with this - http://go.sitepoint.com/t/y-l-drkhttd-jdiyoktlk-j/ there is a free copy :) – Craig van Tonder Aug 24 '15 at 01:51
  • @IndigoIdentity good advice...I will take you up on that – Michael E Aug 24 '15 at 02:07
  • Although you may need to understand some PHP to accomplish this you would ultimately be far better off using Javascript on the client side at least. I am struggling to see this game take off where everything you do requires a page load. Do the course, you will have made a good step forward! – Craig van Tonder Aug 24 '15 at 02:24
  • @MichaelE - do you want to display them ascendingly or descendingly? – Logan Wayne Aug 24 '15 at 05:27

1 Answers1

1

Note:

  • You want to fetch data from your database, and it will dynamically fetch new data within 30 seconds, right? So, do you want the new data at the top or at the bottom?
  • In order to achieve your goals, we will be using jQuery (a Javascript library) and Ajax
  • I'll be using mysqli_* prepared statement so you don't need to worry about SQL injections
  • I'll be guiding you through the code by leaving explanations quoted in /**/ and <!-- -->

Lets first establish a connection and store it in a separate file (say connection.php):

<?php

  /* ESTABLISH YOUR CONNECTION */
  $con = new mysqli("localhost", "username", "password", "dbname");
  /* CHECK CONNECTION */
  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
  }

?>

We can now fetch all the existing data and store them in a table (your main file - index.php?):

<table id="table">
  <tr>
    <th>id</th>
    <th>player</th>
    <th>brand</th>
    <th>year</th>
  </tr>

<?php

  include("connection.php"); /* INCLUDE YOUR CONNECTION TO YOUR DATABASE */

  if($stmt = $con->prepare("SELECT id, player, brand, year FROM bbcardindo")){ /* CHECK IF THE PREPARED STATEMENT IS TRUE */
    $stmt->execute(); /* EXECUTE THE QUERY */
    $stmt->bind_result($id,$player,$brand,$year); /* BIND THE RESULT TO THESE VARIABLES */
    while($stmt->fetch()){ /* START LOOP THAT WILL FETCH ALL ROWS */
      ?>
        <tr>
          <td><?php echo $id; ?></td>
          <td><?php echo $player; ?></td>
          <td><?php echo $brand; ?></td>
          <td><?php echo $year; ?></td>
        </tr>
      <?php
    } /* END OF WHILE LOOP */
    $stmt->close(); /* CLOSE THE STATEMENT */
  } /* END OF PREPARED STATEMENT */

?>
</table> <!-- END OF TABLE -->
<input type="hidden" id="lastid" value="<?php echo $id; ?>">
<!-- WE WILL BE STORING THE LAST/LATEST ID IN A HIDDEN INPUT FIELD THAT WE WILL BE USING FOR OUR SCRIPT LATER -->

Download the jQuery library here and put it inside your project folder. Then let us create the script that you will be needing to fetch new data every 30 seconds (you can put this at the top of our first code; this is still part of your main file - index.php):

<script src="jquery-1.11.3.js"></script> <!-- CHANGE THE NECESSARY JS FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script type="text/javascript">
  $(document).ready(function(){ /* START THE JQUERY */
    setInterval(function() { /* START THE setInterval FUNCTION */

      var lastid = $("#lastid").val(); /* GET THE VALUE OF THE HIDDEN INPUT FIELD */
      var dataString = 'lastid=' + lastid; /* STORE IT AS A DATA STRING */

      $.ajax({ /* START THE AJAX */
        type: "POST", /* METHOD WE WILL BE USING TO PASS THE FORM */
        url: "getnewdata.php", /* FILE WHERE WE WILL PASS THE DATA */
        dataType: 'json', /* USE JSON AS THE DATATYPE FOR READING DATA BEING RETURNED FROM getnewdata.php */
        data: dataString, /* THE DATA THAT WE WILL BE PASSING IN getnewdata.php */
        success: function(result){
          if(result.newid != ""){ /* IF THIS PASSES A NEW DATA */
            $('#table tr:last').after(result.newtr); /* APPEND TO YOUR TABLE THE NEW DATA */
            $("#lastid").val(result.newid); /* UPDATE THE HIDDEN INPUT FIELD WITH THE LATEST INSERTED ID */
          } /* END OF CHECKING RETURNED DATA */
        } /* END OF SUCCESS */
      }); /* END OF AJAX */

      return false;
    }, 30000); /* SET TO 30 SECONDS */
  }); /* END OF JQUERY */
</script>

Then create the file where we will get new data (getnewdata.php):

<?php

  include("connection.php");

  if(!empty($_POST["lastid"])){ /* IF THERE IS A PASSED DATA */

    $newtr = '';
    $newestid = '';

    if($stmt = $con->prepare("SELECT id,player,brand,year FROM bbcardindo WHERE id > ?")){ /* GET ROWS GREATER THAN THE PASSED ON ID; CHECK IF THE PREPARED STATEMENT IS TRUE */
      $stmt->bind_param("i",$_POST["lastid"]); /* BIND THE PASSED ON DATA TO THE QUERY; i STANDS FOR INTEGER, MEANING THAT WE WILL BIND A NUMERIC VALUE TO THE QUERY */
      $stmt->execute(); /* EXECUTE THE QUERY */
      $stmt->bind_result($id,$player,$brand,$year); /* STORE THE DATA TO THESE VARIABLES */
      while($stmt->fetch()){ /* START FETCHING NEW ROWS */
        $newtr = '
          <tr>
            <td>'.$id.'</td>
            <td>'.$player.'</td>
            <td>'.$brand.'</td>
            <td>'.$year.'</td>
          </tr>
        ';
        $newestid = $id; /* STORE THE LAST ID */
      } /* END OF WHILE LOOP OF FETCHING NEW DATA */
    } /* END OF PREPARED STATEMENT */
    echo json_encode(array("newtr" => $newtr, "newid" => $newestid)); /* PRINT THE RESULT IN JSON */
  } /* END OF IF NOT EMPTY lastid */

?>

Review:

When you load your main file (index.php), all the existing data from your bbcardindo table will be listed in a table. The latest id will be stored in a hidden input field. Every 30 seconds, the program will check for new data based from the hidden input field. New data will be added as new row(s) automatically at the bottom of your table.

Community
  • 1
  • 1
Logan Wayne
  • 6,001
  • 16
  • 31
  • 49