-1

我正在尝试使用一个查询获取邮政编码,并将其用于另一个查询的 where 子句。

<?php
$mobile = '07790807055';
//$mobile = $_POST['mobile'];


mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());

$query =("SELECT POSTCODE FROM appregistration WHERE MOBILE_NUMBER = '$mobile'");
$result = mysql_query ($query) or die ("Unable to connect. " . mysql_error());
$row = mysql_fetch_array($result);
$postcode = $row['POSTCODE'];
/// gets postcode from appregistration table 

$sql=mysql_query("SELECT INCIDENT_ID, INVESTIGATION,TYPE_OF_INCIDENT,DESCRIPTION FROM appreports WHERE POSTCODE = '$postcode'");
//uses postcode from ppregistration table  to find info from appreports table 

while($row=mysql_fetch_assoc($sql)) $output[]=$row;

print(json_encode($output));

mysql_close();
?>
4

2 回答 2

2

为什么不使用JOIN而不是运行两个查询:

SELECT `INCIDENT_ID`, `INVESTIGATION`, `TYPE_OF_INCIDENT`, `DESCRIPTION`
FROM `appreports`
INNER JOIN `appregistration` ON `appreports`.`POSTCODE` = `appregistration`.`POSTCODE`
WHERE `appregistration`.`MOBILE_NUMBER` = '$mobile'

例如:

<?php
$mobile = '07790807055';

mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());

$sql = mysql_query("SELECT `INCIDENT_ID`, `INVESTIGATION`, `TYPE_OF_INCIDENT`, `DESCRIPTION`
                    FROM `appreports`
                    INNER JOIN `appregistration` 
                    ON `appreports`.`POSTCODE` = `appregistration`.`POSTCODE`
                    WHERE `appregistration`.`MOBILE_NUMBER` = '$mobile'");

while($row=mysql_fetch_assoc($sql))
{
    $output[] = $row;
}

print(json_encode($output));

mysql_close();
?>
于 2013-03-05T20:50:01.927 回答
0

撇开明显的 SQL 注入漏洞、代码中可疑的注释(多余的标点符号)、不推荐使用的 API 和对 mysql_fetch_array() 调用中默认参数的依赖、不必要的拆分查询以及其他一些应该注意的事情不谈在任何代码审查中都被选中,但实际上并不会影响功能……您实际上并没有说出运行代码时会发生什么。

第一个查询是否返回结果?

当您通过 mysql CLI 或 phpmyadmin 运行查询时会发生什么?

更新

如果我使用 join "Parse error: syntax error, unexpected '`' on line 20,这就是我遇到的错误

好的,这导致问题的 SQL 注入错误 - 我假设这是第 20 行:

$sql=mysql_query("SELECT INCIDENT_ID, INVESTIGATION,TYPE_OF_INCIDENT
      ,DESCRIPTION FROM appreports WHERE POSTCODE = '$postcode'");

$postcode 包含一个或多个单引号。逃脱它:

    $sql=mysql_query("SELECT INCIDENT_ID, INVESTIGATION,TYPE_OF_INCIDENT
      ,DESCRIPTION FROM appreports WHERE POSTCODE = '".
      mysql_real_escape_string($postcode) . "'");
于 2013-03-05T20:54:17.133 回答