我正在尝试使用一个查询获取邮政编码,并在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();
?>
答案 0 :(得分: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();
?>
答案 1 :(得分:0)
不考虑明显的SQL注入漏洞,代码中的可疑注释(冗余标点符号),不推荐使用的API以及对mysql_fetch_array()调用中的默认参数的依赖,不必要的拆分查询以及其他一些事情应该在任何代码审查中选择,但实际上不会影响功能....实际上并没有说明运行代码时会发生什么。
第一个查询是否返回结果?
通过mysql CLI或phpmyadmin运行查询时会发生什么?
<强>更新强>
如果我使用join“解析错误:语法错误,第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) . "'");