将值添加到sql数据库后,PHP / Ajax自动刷新

时间:2017-04-26 14:26:04

标签: php mysql ajax

抱歉我的英文。 我尝试修改此脚本,该脚本使用AJAX查找数据库表中的更改,如果检测到更改,则返回该表中的信息:http://blog.codebusters.pl/en/ajax-auto-refresh-volume-ii/

我没有使用html表单向数据库添加值(来自add.php),而是在页面加载时尝试向db发送值(目标是实时警告用户在该页面上)

我认为需要修改的文件是add.php,尤其是:

"<?php require('common.php');
if($_POST && !empty($_POST['title'])){
$result = $db->add_news(strip_tags($_POST['title']));
}?>"

我重申:

<?php

$link = mysqli_connect("localhost", "user", "mypass", "db");

if($link === false){

    die("ERROR: Could not connect. " . mysqli_connect_error());

}

$sql = "INSERT INTO news (title) VALUES ('This page has been loaded !')";

if(mysqli_query($link, $sql)){

    echo "Records inserted successfully.";

} else{

    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);

}
mysqli_close($link);
?>

问题是自动刷新无效。我想这是因为add.php中缺少这一行:

"$result = $db->add_news(strip_tags($_POST['title']));"

在sql表中添加值后如何请求自动刷新? 我想我必须使用db.php中的函数register_changes,但我不知道如何以及在哪里......我是初学者而且输了!

提前感谢您的帮助。

以下是原始文件:

add.php:

<?php require('common.php');
if($_POST && !empty($_POST['title'])){
    $result = $db->add_news(strip_tags($_POST['title']));
}?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Add news - Demo for Ajax Autorefresh</title>
</head>
<body>
    <h1>This is a demo for post <a href="http://blog.codebusters.pl/en/entry/ajax-auto-refresh-volume-ii">Ajax Auto Refresh - Volume II</a></h1>
    <p>Open <a href="index.php">list of messages</a> in new window, add new message with this form and look at that list. Don't refresh it manually. It should refresh automatically after 20 seconds.<p>
    <?php if(isset($result)){
        if($result==TRUE){
            echo '<p>Success</p>';
        }else{
            echo '<p>Error</p>';
        }
    }else{?>
        <form method="post" action="#">
            <input type="text" name="title" size="50" />
            <input type="submit" value="Add message" />
        </form>
    <?php }?>
</body>
</html>

common.php:

<?php
require_once ('db.php'); //get our database class
$db = new db();
/* end of file common.php */

db.php:

<?php
/**
 * Class db for Ajax Auto Refresh - Volume II - demo
 *
 * @author Eliza Witkowska <kokers@codebusters.pl>
 * @link http://blog.codebusters.pl/en/entry/ajax-auto-refresh-volume-ii
 */
class db{

    /**
     * db
     *
     * @var $   public $db;
     */
    public $db;


    /**
     * __construct
     *
     * @return void
     */
    function __construct(){
        $this->db_connect('localhost','root','alamakota','test');
    }


    /**
     * db_connect
     *
     * Connect with database
     *
     * @param mixed $host
     * @param mixed $user
     * @param mixed $pass
     * @param mixed $database
     * @return void
     */
    function db_connect($host,$user,$pass,$database){
        $this->db = new mysqli($host, $user, $pass, $database);

        if($this->db->connect_errno > 0){
            die('Unable to connect to database [' . $this->db->connect_error . ']');
        }
    }


    /**
     * check_changes
     *
     * Get counter value from database
     *
     * @return void
     */
    function check_changes(){
        $result = $this->db->query('SELECT counting FROM news WHERE id=1');
        if($result = $result->fetch_object()){
            return $result->counting;
        }
        return 0;
    }


    /**
     * register_changes
     *
     * Increase value of counter in database. Should be called everytime when
     * something change (add,edit or delete)
     *
     * @return void
     */
    function register_changes(){
        $this->db->query('UPDATE news SET counting = counting + 1 WHERE id=1');
    }


    /**
     * get_news
     *
     * Get list of news
     *
     * @return void
     */
    function get_news(){
        if($result = $this->db->query('SELECT * FROM news WHERE id<>1 ORDER BY add_date DESC LIMIT 50')){
            $return = '';
            while($r = $result->fetch_object()){
                $return .= '<p>id: '.$r->id.' | '.htmlspecialchars($r->title).'</p>';
                $return .= '<hr/>';
            }
            return $return;
        }
    }


    /**
     * add_news
     *
     * Add new message
     *
     * @param mixed $title
     * @return void
     */
    function add_news($title){
        $title = $this->db->real_escape_string($title);
        if($this->db->query('INSERT into news (title) VALUES ("'.$title.'")')){
            $this->register_changes();
            return TRUE;
        }
        return FALSE;
    }
}
/* End of file db.php */

index.php:

<?php require('common.php'); ?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo for Ajax Auto Refresh</title>
    <script src="jquery-1.10.2.min.js"></script>
    <script>
        /* AJAX request to checker */
        function check(){
            $.ajax({
                type: 'POST',
                url: 'checker.php',
                dataType: 'json',
                data: {
                    counter:$('#message-list').data('counter')
                }
            }).done(function( response ) {
                /* update counter */
                $('#message-list').data('counter',response.current);
                /* check if with response we got a new update */
                if(response.update==true){
                    $('#message-list').html(response.news);
                }
            });
        }
        //Every 20 sec check if there is new update
        setInterval(check,20000);
    </script>
</head>
<body>
    <h1>This is a demo for post <a href="http://blog.codebusters.pl/en/entry/ajax-auto-refresh-volume-ii">Ajax Auto Refresh - Volume II</a></h1>
    <?php /* Our message container. data-counter should contain initial value of couner from database */ ?>
    <div id="message-list" data-counter="<?php echo (int)$db->check_changes();?>">
        <?php echo $db->get_news();?>
    </div>
    <p><a href="add.php">Add new message</a></p>
</body>
</html>

checker.php:

<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
    //the counters are diffrent so get new message list
    $data['news'] = '<h1>OMG! It\'s alive!!! NEW UPDATE !!!</h1>';
    $data['news'] .= $db->get_news();
    $data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */

1 个答案:

答案 0 :(得分:0)

最后我通过添加到我的文件末尾(在mysqli_close之后)解决了我的问题:

$db->register_changes();

自动刷新再次工作。