查询不从表中获取数据

时间:2013-07-13 07:45:31

标签: php mysql

我的问题是,当我直接在MySQL中运行查询时,它可以工作:

SELECT * FROM SubCategoryLookup  WHERE LinkedCategoryID = '4' AND OrganizationCode = 'ibm'

使用PHP时,如果我给出任何变量,那么它就不会得到记录:

$OrganizationCode=$_REQUEST['OrganizationCode'];
echo($OrganizationCode);

$CategoryId=$_REQUEST['CategoryId'];
echo($CategoryId);

$query = mysql_query("SELECT *
                        FROM SubCategoryLookup
                       WHERE LinkedCategoryID = '$CategoryId'
                             AND OrganizationCode = '$OrganizationCode'");
echo($query);

$rows = array();
while($row = mysql_fetch_assoc($query))
{
    $rows[] = $row;
}
echo json_encode($rows);

当我使用网址访问此内容时:

http://www.celeritas-solutions.com/pah_brd_v1/productivo/getSubCategory.php?OrganizationCode=celeritasCategoryId=3

以下是未显示记录的结果

celeritasCategoryId=3Resource id #3[]

2 个答案:

答案 0 :(得分:1)

您的网址上缺少&,应该是:

http://www.celeritas-solutions.com/pah_brd_v1/productivo/getSubCategory.php?OrganizationCode=celeritas&CategoryId=3

仔细看看,你有:

OrganizationCode=celeritasCategoryId=3

应该是:

OrganizationCode=celeritas&CategoryId=3

导致$CategoryId未设置(或者换句话说为空)会导致查询失败并且不会给您带来任何结果。

您应该使用isset来确保设置变量:

$OrganizationCode = $_GET['OrganizationCode'];
if (!isset($OrganizationCode))
    die("There is no organization code...");

$CategoryId = $_GET['CategoryId'];
if (!isset($CategoryId))
    die("There is no category id...");

除了清理它以防止使用mysql-real-escape-string进行注入并正确使用错误处理程序来了解查询是否因mysql_error而失败:

$sql = sprintf("SELECT * 
                  FROM SubCategoryLookup 
                 WHERE LinkedCategoryID='%s' AND 
                       OrganizationCode='%s'",
               mysql_real_escape_string($CategoryId),
               mysql_real_escape_string($OrganizationCode));

$query = mysql_query($sql);

// change $link to the name of your database connection variable
if (!$query)
    die('Query failed (' . mysql_errno($link) . '): ' . mysql_error($link));

mysql_*个功能不再支持,它们为officially deprecated不再维护,将为removed个未来。您应该使用PDOMySQLi更新代码,以确保将来的项目功能。


以下是你将得到的:

 [{
     "SubCategoryID": "8",
     "LinkedCategoryID": "3",
     "SubCategoryTitle": "Projects: Client A",
     "SubCategoryAddedDateTime": "2013-07-12 23:16:25",
     "SubCategoryAddedByUserID": "1",
     "OrganizationCode": "celeritas"
 }, {
     "SubCategoryID": "9",
     "LinkedCategoryID": "3",
     "SubCategoryTitle": "Projects: Client B",
     "SubCategoryAddedDateTime": "2013-07-12 23:16:25",
     "SubCategoryAddedByUserID": "1",
     "OrganizationCode": "celeritas"
 }, {
     "SubCategoryID": "10",
     "LinkedCategoryID": "3",
     "SubCategoryTitle": "Projects: Client C",
     "SubCategoryAddedDateTime": "2013-07-12 23:16:25",
     "SubCategoryAddedByUserID": "1",
     "OrganizationCode": "celeritas"
 }]

答案 1 :(得分:0)

确保$ rows数组是正确的。 在执行json_encode之前打印它。

删除数组分配代码并添加此

array_push($rows,$row)

然后打印$ rows