PHP - 从MySQL创建显示图片的新闻源(存储路径)

时间:2015-08-24 00:39:03

标签: php mysql mysqli

我正在寻找一个搜索MySQL表的初学者代码,并显示3列数据和由各个表分隔的图片(存储路径):

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

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

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

我需要这个每30秒搜索一次新条目。任何帮助表示赞赏。

PHP代码:

<?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);
?>

数据库:

 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

数据库记录:

+----------------------------------+
| id | player       | brand | year | 
| 1  | jose conseco | Topps | 1989 |
| 2  | andre dawson | score | 1992 |
+----------------------------------+

1 个答案:

答案 0 :(得分:1)

注意:

  • 您想从数据库中获取数据,它会在30秒内动态获取新数据,对吧?那么,您希望新数据位于顶部还是底部?
  • 为了实现您的目标,我们将使用jQuery Javascript库)和Ajax
  • 我将使用mysqli_* prepared statement,因此您不必担心SQL injections
  • 我将在/**/<!-- -->
  • 中引用解释,引导您完成代码。

让我们首先建立连接并将其存储在一个单独的文件中(例如 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();
  }

?>

我们现在可以获取所有现有数据并将它们存储在一个表中(您的主文件 - 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 -->

下载jQuery库here并将其放在项目文件夹中。然后让我们创建每30秒需要获取新数据的脚本(您可以将它放在我们的第一个代码的顶部;这仍然是主文件的一部分 - 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>

然后创建我们将获取新数据的文件( 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 */

?>

修改:

加载主文件( index.php )时,bbcardindo表中的所有现有数据都将列在表格中。最新的id将存储在隐藏的输入字段中。每30秒,程序将根据隐藏的输入字段检查新数据。新数据将自动添加为表格底部的新行。