2015-12-31 26 views
1

我使用伊麗莎Witkowska的Ajax自動刷新代碼:http://blog.codebusters.pl/en/entry/ajax-auto-refresh-volume-iiAjax的自動刷新 - PHP變量不正確地傳遞到自動刷新功能

我已經改變了代碼,這樣我可以通過從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

我認爲問題是變量在包含數據庫連接時不可用checker.php〜聲明變量然後包含db連接。

另外,我建議,而不是使用global表達式來定義您的db類方法中的變量,而不是將它們作爲參數傳遞給它們。我希望以下幾點可能會有用 - 它沒有經過測試。這種在sql中使用變量的方法存在或應該擔心 - 易受可怕sql injection的影響 - 最好在db類中使用prepared statements,並將$agentID$UserIDbind_param()方法綁定。

<?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> 
+0

哇,謝謝一噸RamRaider,我真的很感激它!我會測試它。 –

+0

不客氣,祝你新年快樂 – RamRaider

+0

它像一個魅力,感謝你RamRaider。對於那些想要使用這個腳本的人,你需要對Eliza的原始腳本進行一些修改。表名需要更改爲「聊天」,聊天表中需要添加一些額外的字段:ChatType,AgentID,UserID –