2009-10-25 23 views
0

是我的JSON的PHP代碼JSON和mysql的問題

include("connect.php"); 
$id = $_GET['lid']; 
function countRec($fname,$tname) { 
$sql = "SELECT * FROM `mail` WHERE confirmed = 'no' AND label_id = '". $id ."'"; 
$result = mysql_query($sql) or die ('test'); 
$num = mysql_num_rows($result); 
return $num; 
} 

$page = $_POST['page']; 
$rp = $_POST['rp']; 
$sortname = $_POST['sortname']; 
$sortorder = $_POST['sortorder']; 

if (!$sortname) $sortname = 'ID'; 
if (!$sortorder) $sortorder = 'desc'; 

    $sort = "ORDER BY $sortname $sortorder"; 

if (!$page) $page = 1; 
if (!$rp) $rp = 10; 

$start = (($page-1) * $rp); 

$limit = "LIMIT $start, $rp"; 

$sql = "SELECT * FROM `mail` WHERE confirmed = 'no' AND label_id = '". $id ."' $sort $limit"; 
$result = mysql_query($sql) or die ('test'); 

$total = countRec(); 

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); 
header("Cache-Control: no-cache, must-revalidate"); 
header("Pragma: no-cache"); 
header("Content-type: text/x-json"); 
$json = ""; 
$json .= "{\n"; 
$json .= "page: $page,\n"; 
$json .= "total: $total,\n"; 
$json .= "rows: ["; 
$rc = false; 
while ($row = mysql_fetch_array($result)) { 
if ($rc) $json .= ","; 
$json .= "\n{"; 
$json .= "id:'".$row['ID']."',"; 
$json .= "cell:['".$row['email']."'"; 
$json .= ",'".addslashes($row['name'])."'"; 
$json .= ",'".addslashes($row['country'])."'"; 
$json .= ",'".addslashes($row['bus'])."'"; 
$json .= ",'".addslashes($row['website'])."'"; 
$json .= ",'".addslashes($row['music'])."'"; 
$json .= ",'".addslashes($row['radio'])."']"; 
$json .= "}"; 
$rc = true; 
} 
$json .= "]\n"; 
$json .= "}"; 
echo $json; 

我張貼數據到這個PHP這樣的 「req.php?蓋= 3434」

,並獲得 「鍋蓋」 一樣$id = $_GET['lid'];你可以看到

但在我的MySQL,當我寫WHERE label_id = '$id'它不工作

有什麼建議?

感謝

回答

3

你引用一個函數內部的全球$id。你需要將其標記爲全球:

function countRec($fname,$tname) { 
    global $id; 
    //etc 
} 

或者你可以把它傳遞給函數的第三個參數,這可能是一個更好的解決方案。

注意,該代碼很容易受到SQL注入式攻擊。您應該報價$id(例如使用mysql_real_escape_string()),或者如果它總是一個整數,你可以將它轉換,例如$id = (int) $id。更妙的是,你可以使用PDO和使用prepared statments and bound parameters,從而消除了這個問題。

+0

omg你是驚人的thx男人 – 2009-10-25 15:21:39

+0

好的,謝謝你的偉大的建議 – 2009-10-25 15:25:39

+0

我會把'$ id'作爲第三個參數,而不是使用'global'。 – cdmckay 2009-10-25 15:51:52