I explode the input of user to array and then search them in the database but if user enter the space as a result it will show the whole rows of the table which has space how can I make it correct?
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());
}
Use trim()
to delete spaces and use mysql_real_escape_string()
to prevent sql injections.
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());
}
}
But it's better to use MySQLi
than the mysql_real_escape_string()
function.
See http://php.net/manual/en/function.mysql-real-escape-string.php
Or PDO with the prepared statements :
http://php.net/manual/en/pdo.prepared-statements.php
Some points: 1. Instead of using for
, use foreach
- it's useful with arrays (like your case)
3.Use PDO
4.read more about the trim
function
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%"));
}