0

I am developing a phonebook application on PHP. After typing 3 characters, the search script is fired. This query works well. But I have discovered that if I enter the search box %%% characters the page lists all the records which I do not want it to do.

$value = "%" . $_POST['value']  .  "%";
$query = $db->prepare("SELECT
                           k.id, 
                           k.name, 
                           k.surname, 
                           k.phone, 
                           k.email, 
                           u.title, 
                           g.job,
                           b.dept
                      FROM 
                           persons k
                           JOIN titles u ON k.title_id = u.id
                           JOIN departments b ON k.dept_id = b.id
                           JOIN jobs g ON k.job_id = g.id
                      WHERE
                           active = 1 AND
                          ( 
                            LOWER(k.name) LIKE :v1 OR
                            LOWER(k.surname) LIKE :v2 OR
                            LOWER(k.phone) LIKE :v3 OR
                            LOWER(k.email) LIKE :v4
                          )
                      ORDER BY
                          dept, 
                          name, 
                          surname"
            );

$query->bindValue(":v1", strtolower($value), PDO::PARAM_STR);
$query->bindValue(":v2", strtolower($value), PDO::PARAM_STR);
$query->bindValue(":v3", strtolower($value), PDO::PARAM_STR);
$query->bindValue(":v4", strtolower($value), PDO::PARAM_STR);

$query->execute();

How can I prevent this bug?

4

2 回答 2

3

禁止(或删除)那些对 特殊的字符的输入like,例如%并在绑定参数时将其添加到字符串中,例如:

$query->bindValue(":v1", strtolower($value) . "%", PDO::PARAM_STR);

或者:

$val2 = strtolower($value) . "%";
$query->bindValue(":v1", $val2, PDO::PARAM_STR);

这可能是最简单的解决方案。

于 2013-05-03T22:04:52.507 回答
1

在执行查询之前验证用户输入。

像这样的东西应该工作:

$search = preg_replace("/[^A-Za-z0-9 ]/", '', $search);

于 2013-05-03T22:06:10.563 回答