PHP / SQL / Json Parse

时间:2013-11-08 05:19:40

标签: php mysql json

我是php的新手,所以我需要一些帮助。我有一段时间......我知道这很简单!

我这里有一个php文件: http://theclackamasprint.net/json.php

它将信息从mysql提取到json。

我想要一个解析网址来分隔文章的catid(未显示)

所以我希望能够打字 http://theclackamasprint.net/json.php?catid=84 http://theclackamasprint.net/json.php?catid=87

等等......并且只有那些catid show

这是我的代码:

$host = "******";
$db = "******";
$user = "******";
$pass = "******";

$connection = mysql_connect($host, $user, $pass);

//Check to see if we can connect to the server
if(!$connection)
{
    die("Database server connection failed.");  
}
else
{
    //Attempt to select the database
    $dbconnect = mysql_select_db($db, $connection);

    //Check to see if we could select the database
    if(!$dbconnect)
    {
        die("Unable to connect to the specified database!");
    }
    else
    {
        $query = "SELECT title FROM tcp_content WHERE catid=84 ORDER BY publish_up DESC LIMIT 20";
        $resultset = mysql_query($query, $connection);

        $records = array();

        //Loop through all our records and add them to our array
        while($r = mysql_fetch_assoc($resultset))
        {
            $records[] = $r;        
        }

        //Output the data as JSON
        echo json_encode($records);
    }


}

1 个答案:

答案 0 :(得分:-1)

最短的解决方案是将catid=84更改为catid=" . $_GET['catid'] . ",从而将catid参数插入到MySQL查询中。

结果行看起来像

$query = "SELECT title FROM tcp_content WHERE catid=" . $_GET['catid'] . " ORDER BY publish_up DESC LIMIT 20";

HOWEVER 这很容易受到SQL注入攻击,所以如果这是为了任何认真的工作,请务必切换到mysqli_query()PDO::query()