使用LIKE时mysql_query返回错误

时间:2012-11-23 17:35:29

标签: php mysql syntax where sql-like

我正在尝试创建一个脚本,该脚本按给定的术语和城市选择给定MySQL列中的所有用户。该城市将特定于该成员,但每个成员可以有3或4个不同的职位(酒保,服务器,主机等)。我试图使用的代码如下,但它给了我一个错误。如果您需要更多信息,请与我们联系。谢谢!

Could not find staff: Unknown column 'Bartender' in 'where clause'

<?php

    $perpage = 15;
    $city = $_GET['city'];
    $type = $_GET['type'];

    if(isset($_GET["page"]))
    {
        $page = intval($_GET["page"]);
    }
    else
    {
        $page = 1;
    }

    $calc = $perpage * $page;
    $start = $calc - $perpage;
    $result = mysql_query("SELECT * FROM staff WHERE titles LIKE $type AND city=$city LIMIT $start, $perpage");
    $rows = mysql_num_rows($result);
    if($rows)
    {
        $i = 0;
        while($post = mysql_fetch_array($result))
        {
?>
            <tr style="background-color: #cccccc;">
                <td style="font-weight: bold;font-family: arial;"><?php echo $post["staffnum"]; ?> >> <?php echo $post["titles"]; ?></td>
            </tr>
            <tr>
                <td style="font-family: arial;padding-left: 20px;"><?php echo $post["abt1"]; ?></td>
            </tr>
<?php
        }
    } else {
          die('Could not find staff: ' . mysql_error());
    }
?>

2 个答案:

答案 0 :(得分:4)

为了根据需要使用LIKE,您需要将其包装在引号中并使用相应的%个字符。

$type = mysql_real_escape_string($_GET['type']);
// do the same with $city and any other user input

$result = mysql_query("SELECT * FROM staff WHERE titles LIKE '%" . $type . "%' AND city='" . $city . "' LIMIT $start, $perpage");

答案 1 :(得分:0)

尝试

$type = mysql_real_escape_string($_GET['type']);
$city = mysql_real_escape_string($_GET['city']);

$result = mysql_query("SELECT * FROM staff WHERE titles LIKE '%$type%' AND city='$city' LIMIT $start, $perpage");