MySql查询来自多个选择表单的结果

时间:2013-11-23 23:50:51

标签: php mysql arrays

我在html页面上有一个表单,允许我选择多个项目。表单的名称是name =“region []

它发布到我使用此代码的另一个页面:

The region(s) selected:
<?php
$values = $_POST['region'];

foreach ($values as $region){
echo $region;
}
?>

这将完美显示表单的结果;如果有一个值,它将打印一个值,但如果有多个值则会打印所有值。

我需要在查询中使用此结果:

<?php
$con=mysqli_connect("****","****","****","****");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT
GoogleBusinessData.BusName,
GoogleBusinessData.BusAddress,
PostcodeTbl.PostcodeFirstTown,
PostcodeTbl.PostcodeFirstArea,
PostcodeTbl.Region,
PostcodeTbl.Postcode,
PostcodeTbl.PostcodeFirstLetters,
PostcodeTbl.PostcodeFirstPart,
PostcodeTbl.Country,
GoogleBusinessData.BusPhone,
GoogleBusinessData.BusCats,
GoogleBusinessData.FaroukCat,
GoogleBusinessData.BusWebsite,
GoogleBusinessData.BusDescription,
GoogleBusinessData.BusGoogleBusinessID,
GoogleBusinessData.BusPageURL,
EmailTable.EmailNumberOfEmails,
EmailTable.EmailAddresses
FROM
GoogleBusinessData
INNER JOIN PostcodeTbl ON GoogleBusinessData.BusPostalCode = PostcodeTbl.Postcode
INNER JOIN EmailTable ON GoogleBusinessData.BusWebsite = EmailTable.EmailWebsite
WHERE EmailTable.EmailNumberOfEmails > 0 AND
GoogleBusinessData.FaroukCat = 'Wedding Planner'
GROUP BY
GoogleBusinessData.BusWebsite
ORDER BY
GoogleBusinessData.BusName ASC
LIMIT 0,20");

while($row = mysqli_fetch_array($result))
{
echo $row['BusName'] . "  -  " . $row['PostcodeFirstTown'] . "  -  " . $row['PostcodeFirstArea'] . "  -  " . $row['Region'] . "  -  " . $row['Postcode'];
echo "<br>";
}

mysqli_close($con);
?>

所以我需要在WHERE中添加条件,只有当它包含一个带有表单的区域时才返回结果。我毫不高兴地尝试了下面的事情:

WHERE PostcodeTbl.Region IN ('$region') AND
EmailTable.EmailNumberOfEmails > 0 AND
GoogleBusinessData.FaroukCat = 'Wedding Planner'

但这只返回最后一个选择(好像只有一个选中)。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

在第一个脚本中,您将循环浏览项目。每个项目逐个放入变量$region。所以在循环之后,$region包含最后一项。如果在那时构造where子句,它解释了为什么查询只返回最后一项。

要解决此问题,您必须构建一个包含区域列表的变量(例如$regions)。

例如:

$regions = "'" . implode($_POST['region'], "','") . "'";

...  WHERE PostcodeTbl.Region IN ('$regions') AND ...

请注意,这可能不安全,因为$ _POST中的输入未经过验证,因此最好循环遍历数组(就像您一样)并在构造{{1}中的字符串时逐个验证每个项目}。您可以使用mysqli_real_escape_string

或者,可以说更好,是使用mysqli的参数绑定功能。这对于数组变量来说有点棘手,但有关如何执行此操作的详细信息已在this question中进行了描述。