0

我创建了一个表单,它将搜索范围的值发送到数据库,但它似乎不起作用。

查询:

$alpha = $_POST['alpha'];
$sql = "SELECT * FROM tbl_members WHERE resultselect=? AND lname LIKE ?;";
$q = $conn->prepare($sql);
$q->execute(array($categoryid,"[".$alpha."]%"));

表格:

<form action="" method="post">
    <button class="btn btn-link" value="abc" name="alpha">A-B-C</button>
    <button class="btn btn-link" value="def" name="alpha">D-E-F</button>
</form>
4

1 回答 1

0

由于您使用的是 Mysql,因此您可以使用REGEXP

$alpha = $_POST['alpha'];
$sql = "SELECT * FROM tbl_members WHERE resultselect=? AND lname REGEXP ?;";
$q = $conn->prepare($sql);
$q->execute(array($categoryid,"^[".$alpha."]"));

LIKE的查询应该看起来像

SELECT * FROM tbl_members 
WHERE resultselect=? 
  AND (lname LIKE 'a%'
   OR  lname LIKE 'b%'
   OR  lname LIKE 'c%')

因此,在这种情况下,您的 php 代码可能是(假设您总是使用三个字符进行搜索)

$alpha = $_POST['alpha'];
$sql = "SELECT * FROM tbl_members 
        WHERE resultselect=? AND lname (lname LIKE ? OR  lname LIKE ? OR  lname LIKE ?);";
$q = $conn->prepare($sql);
$q->execute(array($categoryid, $alpha[0].'%', $alpha[1].'%', $alpha[2].'%'));

要按字母顺序排列结果集,请使用ORDER BY lname.

这是两者的SQLFiddle演示LIKEREGEXP

于 2013-05-31T04:43:00.193 回答