首页 文章

Ajax自动刷新 - PHP变量未正确传递到自动刷新功能

提问于
浏览
1

我'm using Eliza Witkowska' s Ajax自动刷新代码:http://blog.codebusters.pl/en/entry/ajax-auto-refresh-volume-ii

我已经改变了代码,所以我可以从url传递变量 . 除了一行代码之外,一切都很好 . 代码行是检查新记录的数据库查询的一部分 . 当我尝试将变量传递给查询时,自动刷新停止工作(所有其他功能继续工作) . 如果我使用静态值,它工作正常 .

静态值(这是有效的)

$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID=3 AND UserID=25');

变量(这不起作用)

$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');

将变量传递到同一脚本中的另一个函数没有问题 . 所以我被困住了几天 . 任何帮助,不胜感激 .

db.php中

class db{

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

function __construct(){
    $this->db_connect('###SERVER###','###USERNAME###','###PASSWORD###','###DATABASE###');   //my database information
}

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 . ']');
    }
}

//////////////////////////////
//This is the function that is having an issue when I pass it variables
//////////////////////////////

function check_changes(){
    global $UserID;     //Declaring my variable
    global $AgentID;    //Declaring my variable
    $result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');

    if($result = $result->fetch_object()){
        return $result->counting;
    }
    return 0;
}


//////////////////////////////
//This function has no problem, even when I pass it variables
//////////////////////////////
function get_news(){
    global $UserID;
    global $AgentID;
    if($result = $this->db->query('SELECT * FROM chats WHERE id<>1 AND AgentID='.$AgentID.' AND UserID='.$UserID.' ORDER BY add_date ASC LIMIT 50')){
        $return = '';
        while($r = $result->fetch_object()){
            if ($r->ChatType==1) {      //ChatType is a field in the table that distinguishes Agent texts from User Texts
                $return .= ''.htmlspecialchars($r->title).'';
            } else {
                $return .= '<div align="right">'.htmlspecialchars($r->title).'</div>';
            }
        }
        return $return;
    }
}


}

以下是其他文件:

的index.php

<?php
$AgentID = $_REQUEST["AgentID"];  //Grabing AgentID from the URL
$UserID = $_REQUEST["UserID"];    //Grabing UserID from the URL
require('common.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin</title>
<script src="jquery-1.10.2.min.js"></script>
<script>
    /* AJAX request to checker */
    function check(){
        $.ajax({
            type: 'POST',
            url: 'checker.php?AgentID=<? echo $AgentID; ?>&UserID=<? echo $UserID; ?>',  //This line has been updated by passing parameters
            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);
                var audio = new Audio('img/solemn.mp3');
                audio.play();
            }
        });
    }
    //Every 2 sec check if there is new update
    setInterval(check,2000);
</script>
<style>
body {
    margin:0px;
    padding:0px;
    vertical-align:top;
}
</style>
</head>
<body>
<?php /* Our message container. data-counter should contain initial value of counter from database */ ?>
<br>
<div id="message-list" data-counter="<?php echo (int)$db->check_changes();?>">
    <?php echo $db->get_news();?>
</div>
</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']){
$AgentID = $_REQUEST["AgentID"];  //passing my variable to db.php
$UserID = $_REQUEST["UserID"];    //passing my variable to db.php
$data['news'] = $db->get_news();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
?>

的common.php

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

1 回答

  • 1

    我认为问题是在 checker.php 中包含数据库连接时变量不可用 - 声明变量然后包含数据库连接 .

    另外,我建议不要使用 global 表达式来定义db类方法中的变量,而是将它们作为参数传递 . 我希望以下可能有用 - 虽然没有经过测试 . 这个在sql中使用变量的方法有或者应该关注 - 它很容易受到可怕的 sql injection ~更好的方法是在db类中使用 prepared statements 并使用 bind_param() 方法绑定 $agentID$UserID .

    <?php
        /* common.php */
    
        $dbhost =   'xxx';
        $dbuser =   'xxx'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'xxx';
    
        require_once 'db.php';
        $db = new db( $dbhost, $dbuser, $dbpwd, $dbname );
    ?>
    
    
    <?php
        /* database class: db.php */
        class db{
            private $db;
    
            public function __construct( $dbhost, $dbuser, $dbpwd, $dbname ){
                $this->db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
                if( $this->db->connect_errno > 0 ) exit('Unable to connect to database [' . $this->db->connect_error . ']');
            }
    
            public function check_changes( $AgentID=false, $UserID=false ){
                if( $AgentID && $UserID ){
                    $result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');
                    if($result = $result->fetch_object()){
                        return $result->counting;
                    }
                }
                return 0;
            }
            public function get_news( $AgentID, $UserID ){
                $return = '';
                if( $AgentID && $UserID ){
                    if( $result = $this->db->query('SELECT * FROM chats WHERE id<>1 AND AgentID='.$AgentID.' AND UserID='.$UserID.' ORDER BY add_date ASC LIMIT 50' ) ){
                        while( $r = $result->fetch_object() ){
                            if ($r->ChatType==1) {
                                $return .= ''.htmlspecialchars($r->title).'';
                            } else {
                                $return .= '<div align="right">'.htmlspecialchars($r->title).'</div>';
                            }
                        }
                    }
                    return $return;
                }
            }
        }
    ?>
    
    
    <?php 
        /* Checker.php */
        $AgentID = isset( $_REQUEST["AgentID"] ) ? $_REQUEST["AgentID"] : false;
        $UserID = isset( $_REQUEST["UserID"] ) ? $_REQUEST["UserID"] : false;   
    
        if( $AgentID && $UserID ){
    
            /* Do SOME filtering of user supplied data */
            $AgentID=filter_var( $AgentID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
            $UserID=filter_var( $UserID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
    
            require 'common.php';
    
            $data['current'] = (int)$db->check_changes( $AgentID, $UserID );
            $data['update'] = false;
    
            if( isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current'] ){
                $data['news'] = $db->get_news( $AgentID, $UserID );
                $data['update'] = true;
            }
            echo json_encode($data);
        }
    ?>
    
    <?php
        $AgentID = isset( $_REQUEST["AgentID"] ) ? $_REQUEST["AgentID"] : false;
        $UserID = isset( $_REQUEST["UserID"] ) ? $_REQUEST["UserID"] : false;
    
        $AgentID=filter_var( $AgentID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
        $UserID=filter_var( $UserID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
    
        require 'common.php';
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Admin</title>
            <script src="jquery-1.10.2.min.js"></script>
            <script>
                <?php
    
                echo "
                    var aid={$AgentID};
                    var uid={$UserID};";
    
                ?>
                function check(){
                    $.ajax({
                        type:'POST',
                        url:'checker.php?AgentID='+aid+'&UserID='+uid,
                        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);
                            var audio = new Audio('img/solemn.mp3');
                            audio.play();
                        }
                    });
                }
                setInterval(check,2000);
            </script>
            <style>
                body {
                    margin:0px;
                    padding:0px;
                    vertical-align:top;
                }
            </style>
        </head>
        <body>
            <br>
            <div id="message-list" data-counter="<?php echo (int)$db->check_changes($AgentID, $UserID); ?>">
                <?php echo $db->get_news($AgentID, $UserID);?>
            </div>
        </body>
    </html>
    

相关问题