0

我将用户的输入分解为数组,然后在数据库中搜索它们,但是如果用户输入空间作为结果,它将显示有空间的表的整行我怎样才能使它正确?

if(isset($_POST['submit'])){
$keywords = explode(" ", $_POST["search"]);
for ($i=0; $i<count($keywords); $i++) {

$query = "SELECT * FROM mp3s " .
"WHERE (artist LIKE '%".$keywords[$i]."%' 
OR   genre LIKE '%".$keywords[$i]."%'  
OR  album LIKE '%".$keywords[$i]."%'
OR  filename LIKE '%".$keywords[$i]."%'
) ";
$sql = mysql_query($query) or die(mysql_error());

}
4

2 回答 2

1

用于trim()删除空格并用于mysql_real_escape_string()防止 sql 注入。

 if(isset($_POST['submit'])){
    $keywords = explode(" ", trim($_POST["search"]));
    for ($i=0; $i<count($keywords); $i++) {

    if(!empty($keywords[$i])) {

      $query = "SELECT * FROM mp3s " .
      "WHERE (artist LIKE '%".trim(mysql_real_escape_string($keywords[$i]))."%' 
      OR   genre LIKE '%".trim(mysql_real_escape_string($keywords[$i]))."%'  
      OR  album LIKE '%".trim(mysql_real_escape_string($keywords[$i]))."%'
      OR  filename LIKE '%".trim(mysql_real_escape_string($keywords[$i]))."%'
      ) ";
      $sql = mysql_query($query) or die(mysql_error());

    }

    }

但它MySQLimysql_real_escape_string()功能更好用。
http://php.net/manual/en/function.mysql-real-escape-string.php

或带有准备好的语句的 PDO:http:
//php.net/manual/en/pdo.prepared-statements.php

于 2012-10-16T12:35:07.230 回答
1

几点: 1. 而不是使用for,使用foreach- 它对数组很有用(就像你的情况一样)

  1. 在执行查询之前检查用户的查询,不要让用户输入超过 2 个字符的关键字(使用'strlen')。

3.使用PDO

4.阅读更多关于trim函数的信息

if(isset($_POST['submit'])){
$search_string = trim($_POST['search']);
if(strlen($search_string) == 0)
{
//The user is looking for empty string...
//Amm...why is he doing it?
exit();
}

$keywords = explode(" ", $_POST["search"]);
foreach($keywords as $keyword)
{
$keyword = trim($keyword);
$stmt = $dbh->prepare("SELECT * FROM mp3s WHERE (artist LIKE ? 
OR   genre LIKE ? OR  album LIKE ? OR  filename LIKE ?)");

$stmt->execute(array("%$keyword%","%$keyword%","%$keyword%","%$keyword%"));

}
于 2012-10-16T12:42:36.940 回答