使用PHP搜索MySQL表

时间:2014-06-04 14:26:18

标签: php mysql forms search

我正在尝试创建一个PHP文件,以帮助从网页搜索MySQL中构建的表。我已经构建了表单,允许用户在两​​个搜索条件中输入关键字,并为第三个搜索条件提供下拉菜单。但是,我在PHP文件本身遇到问题。我似乎做错了什么,不能弄清楚出了什么问题。如果有人能在下面的代码中发现错误,我真的很感激帮助。 感谢。

// define variables and set to empty values
$Location = $Commemorating =  "";
if (isset($_GET['Region']) && !empty($_GET['Region'])) 
{
    $Region_name = $_GET['Region'];

    if (empty($_GET["Location"])) 
    {
        $Location = "";
    } 
    else 
    {
        $Location = ($_GET["Location"]);
    }

    if (empty($_GET["Commemorating"])) 
    {
        $Commemorating = "";
    } 
    else 
    {
        $Commemorating = ($_GET["Commemorating"]);
    }

$query = "SELECT Monument,
                Location,
                Commemorating,
                Region,

        FROM MONUMENTS 
        WHERE Region = '$Region'";
        //..if a location is specified run this query
        if ($Location != "") 
        {
            $query .= " AND Location LIKE '%$Location%'";
        }
        //..and if a name is entered run this query
        if ($Commemorating != "") 
        {
            $query .= " AND Commemorating LIKE '%$Commemorating%'";
        } 
        //..and if a region is specified run this query
        if ($Region != "All") 
        {
            $query .= " AND Region LIKE '$Region'";
        }
$query_run = mysql_query($query);
}

2 个答案:

答案 0 :(得分:1)

$query = "SELECT Monument,
            Location,
            Commemorating,
            Region,

看起来你应该从查询中删除字段列表中的列表逗号:

$query = "SELECT Monument,
            Location,
            Commemorating,
            Region

喜欢这个。

由于您检查Region是否为空,然后查询给定Region中的项目然后在Region不是'All'的情况下添加其他原因,因此存在一些误解。因此,如果我使用Region = 'All'运行您的代码,那么查询将只返回区域设置为“全部”的项目,这听起来有点奇怪(我说古迹是在一个区域,不是它?)。

您还可以使用LIKE,因为您可以简单地使用=,因为您在字符串周围添加了sibgle引号('),因此它不会为您提供任何“通配符”匹配但会减慢查询。另一件事是做一些mysql转义函数,以确保你不会在你的一个GET查询中获得SQL代码。

我还建议您稍微缩短一下代码:

$Region_name = isset($_GET['Region']) ? trim($_GET['Region']) : '';
if ($Region_name) {
    $Location = isset($_GET['Location']) ? trim($_GET['Location']) : '';
    $Commemorating = isset($_GET['Commemorating']) ? trim($_GET['Commemorating']) : '';
    $query = sprintf("SELECT 
                    Monument,
                    Location,
                    Commemorating,
                    Region
            FROM MONUMENTS
            WHERE 1=1%s%s%s",
                    $Region!='All' ? "AND Region='".mysql_real_escape_string($Region)."'",
                    $Location ? "AND Location='".mysql_real_escape_string($Location)."'",
                    $Commemorating ? "AND Region = '".mysql_real_escape_string($Region)."'",
    );
    ...etc...

我添加了1=1,因此我可以轻松地将AND添加到以下原因中而不用担心。

答案 1 :(得分:0)

在查询中使用$ Region_name而不是$ Region。我看到你依赖于用户输入(通过$ _GET)。确保您清理用户输入:https://stackoverflow.com/a/3126175/1071063