仅获取新的条目数据库mysql

时间:2015-09-20 19:34:26

标签: php jquery mysql ajax

我需要一点帮助..我想在我的数据库中只获取新条目而不刷新我的页面.. ii有一个php页面,可以显示我的数据库的所有记录..就像有人在数据库中输入新数据我想只获取单个entery ..不要再次获取所有条目..我也读过有太多关于JSON ajax等的文章..但是没有人帮助我获取只有单个entery。在这里任何方式使用xml或特殊的东西这样做..我不知道我怎么能这样做 谢谢

1 个答案:

答案 0 :(得分:2)

一种非常通用的方法是这样的:

在每个页面加载运行一个脚本,该脚本每隔一定时间间隔检查数据库中的新条目:

使用Javascript:

<script>
$(document).ready(function(){
    setInterval(function(){
        $.ajax({
            type: 'POST',
            url: 'ajaxfile.php'
        }).success(function(response){
            var response = $.parseJSON(response);
            var username = response.username; //here we put hypothetical db column "username" in a variable
            alert(username); //here we alert the "username" variable in order to verify the script. All other db columns can be called as: response.db_column_name
        });
    }, 10000); //interval time: 10000 milliseconds (10 seconds)
});
</script>

此脚本与以下“ajaxfile.php”结合使用,将显示所有数据库列:response.db_column

在我向您提供关于'ajaxfile.php'的想法之前,请记住,为了使这种方法起作用,您需要在db表中添加一个额外的列(例如列:“see” - 取值为1或0,并且每添加一个新行,默认值为1。由于您没有提供足够的信息,我将在此假设数据库表称为“用户”,并且 - 您希望实时监控每个新用户注册(间隔10秒)。

PHP(ajaxfile.php)

<?php
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}

require("db_connect.php"); //a typical db connection function

$results = array(); //define the results variable

$query = mysql_query("SELECT * FROM users WHERE new_column = '1' ORDER BY id DESC LIMIT 1"); //here we query the db to fetch only the newest record -the one where column "seen" is "1"

while($res = mysql_fetch_assoc($query)){
    $current_id = $res["id"];
    mysql_query("UPDATE users SET new_column = '0' WHERE id = '$current_id' "); //update the record so it will appear as "seen" and will not be fetched again
    $results[] = $res;
}

echo json_encode($results);

?> 

在上面的文件中,注意前两行是为了保护ajax文件免受直接的“浏览器调用”。这是一个非常通用的解决方案,可以在所有ajax文件中使用。

最后,这是db_connect.php文件的一个示例:

<?php

define('DB_HOST', 'localhost'); // the database host
define('DB_PORT', '3306'); // the database port
define('DB_NAME', 'your_db_name'); // the database name
define('DB_USER', 'your_db_user'); // the database user
define('DB_PASSWORD', 'your_db_password'); // the database password

$conn = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Could not connect to the Database Server");  
mysql_select_db(DB_NAME, $conn) or die("Could not find the Database");

?>

这确实是一种非常通用的方法,但可以通过少量修改或添加来涵盖广泛的应用。 对不起,我不能更具体 - 但你的问题也有点过于“笼统”......希望这对你和其他人有所帮助。