2015-06-28 38 views
0

我的問題是如何獲得的數據庫信息(在我的情況下點只是一個數字)從PHP文件,所以在這裏jQuery的AJAX腳本是我的jquery:如何從php文件得到jQuery的功能信息

function rate_down(id) { 
    var id = id; 
//submit data to php script 

    var data = { 
     "id": id, 
    }; 

    $.ajax({ 
     type: "POST", 
     url: "rating.php", 
     data: data, 
     success: function(response) { 

     var currentValue = /* here i want to put the db number */ 
     var newValue = +currentValue - 1; 
     $("#points_"+id).text(newValue); 




     }, 
     error: function(jqXHR, textStatus, errorThrown){ 
     alert(errorThrown); 
     } 
    }); 
}; 

而我想要我的raiting.php。我不知道我是否應該發佈它,因爲它的無用的,但這裏是我的MySQL查詢在raiting.php:

$pic_id = (int) $_REQUEST['id']; 
mysql_query = mysql_query"SELECT points FROM `photos` WHERE `id` = '$pic_id'"; 
+0

安全注意:在使用MySQL查詢一樣,很容易出現SQL注入。在您的系統的生產環境中非常沮喪;) –

回答

0

問題是在你的PHP腳本。請不要使用mysql_query。使用PDO

$pic_id = (int) $_REQUEST['id']; 

$db = new PDO("..."); 
$q = $db->prepare("SELECT points FROM `photos` WHERE `id` = :pic_id"); 
$q->bindValue(':pic_id', $pic_id); 
$q->execute(); 

if ($q->rowCount() > 0){ 
    $check = $q->fetch(PDO::FETCH_ASSOC); 
    $points = $check['points']; 
}else{ 
    $points = 0; 
} 

echo $points; 

然後在你的Ajax功能:

$.ajax({ 
    type: "POST", 
    url: "rating.php", 
    data: data, 
    success: function(response) { 

     if(response != 0) { 
      var currentValue = response; 
      var newValue = +currentValue - 1; 
      $("#points_"+id).text(newValue); 
     } 

    }, 
    error: function(jqXHR, textStatus, errorThrown){ 
    alert(errorThrown); 
    } 
});