将变量从输入框传递到调用SQL Server的PHP脚本

时间:2014-04-02 14:15:23

标签: php mysql sql

我在将信息从表单传递到PHP脚本时遇到了一些问题,然后PHP脚本从MySQL请求数据。

只要我对请求进行硬编码,我就会获得数据返回;但是,我正在尝试这样做,以便当用户从下拉列表中选择一个选项以使其运行所选查询时。这就是我的形式。

<form action="FETCH.PHP" method="POST" enctype="multipart/form-data">
<select name="mySelect">
<option value="South Yorkshire">South Yorkshire</option>
<option value="West Midlands">West Midlands</option>
</select>
<input type="submit" value="Go">
</form>

这就是我在PHP脚本中的内容:

<?php
$con=mysqli_connect("*******","*******","*******","*******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$selectedOption = $_POST["mySelect"];
$result = mysqli_query($con,"SELECT * FROM `SouthYorkshire` WHERE  `EstProv` ='$_POST'");

echo "<div id=Results>";

while($row = mysqli_fetch_array($result))
{
echo "<div class=ClubName>";
echo $row['EstName'];
echo "<div class=Location>";
echo $row['EstAddress2'];
echo "<br>";
}
echo date("Y") . " " ."Search is Powered by PHP.";
mysqli_close($con);
?>

我知道这里有问题,但我不知道是什么。这是我第一次尝试使用MySQL和PHP。

当前脚本不会出现任何错误,但不会带来任何结果。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

这就是问题所在:

$result = mysqli_query($con,
    "SELECT * FROM `SouthYorkshire` WHERE  `EstProv` ='$_POST'");

将该行更改为:

$result = mysqli_query($con,
    "SELECT * FROM `SouthYorkshire` WHERE  `EstProv` ='$selectedOption'");

<强>更新

您应该绑定params以保护您的脚本,如下所示:

$result = mysqli_query($con,
    sprintf("SELECT * FROM `SouthYorkshire` WHERE  `EstProv` = '%s'",
        preg_replace("/[^A-Za-z ]/", '', $selectedOption))); // pattern based on your html select options

... OR

以面向对象的方式进行:http://php.net/manual/en/mysqli.prepare.php

答案 1 :(得分:1)

WHERE  `EstProv` ='$selectedOption'

答案 2 :(得分:1)

在你的SQL中,你将整个$ _POST放入,并且为了显示结果,没有关闭div标签。