【问题标题】:Json and Mysql problemJson和Mysql问题
【发布时间】:2009-10-25 15:10:09
【问题描述】:

这是我的 json php 代码

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;

我正在像“req.php?lid=3434”一样向这个 php 发布数据

如你所见,得到像 $id = $_GET['lid']; 这样的“盖子”

但是在我的mysql中,当我写WHERE label_id = '$id'它不起作用

有什么建议吗?

谢谢

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    您在函数内引用全局 $id。您需要将其标记为全局:

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

    或者你可以将它作为第三个参数传递给函数,这可能是一个更好的解决方案。

    请注意,此代码容易受到 SQL 注入攻击。你应该引用$id(例如使用mysql_real_escape_string()),或者如果它总是一个整数,你可以转换它,例如$id = (int) $id。更好的是,您可以使用PDOprepared statments and bound parameters,这样就可以解决这个问题。

    【讨论】:

    • 我会将$id 作为第三个参数,而不是使用global
    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 2014-12-05
    • 1970-01-01
    • 2017-03-07
    • 2011-03-10
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    相关资源
    最近更新 更多