我将用户的输入分解为数组,然后在数据库中搜索它们,但如果用户输入空格,那么它将显示具有空格的表的整行,如何才能使其正确?
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());
}
答案 0 :(得分: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());
}
}
但使用MySQLi
比使用mysql_real_escape_string()
功能更好
见http://php.net/manual/en/function.mysql-real-escape-string.php
或PDO准备好的陈述:
http://php.net/manual/en/pdo.prepared-statements.php
答案 1 :(得分:1)
有些观点:
1.使用for
而不是使用foreach
- 它对数组很有用(就像你的情况一样)
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%"));
}