2013-03-09 11 views
0

J'ai des problèmes avec mon module de recherche sur mon site Web. J'utilise ce code:problèmes avec mon module de recherche sur mon site Web

if(!isset($_POST['search'])) { 
$query = "SELECT id, title FROM cars ORDER BY id LIMIT ? OFFSET ?"; 
} 
if(isset($_POST['search']) && $_POST['categories'] != "all") { 
$query = "SELECT id, title FROM cars WHERE title LIKE CONCAT(?, '%') ESCAPE '+' AND category = ? ORDER BY id LIMIT ? OFFSET ?"; 
} 
if(isset($_POST['search']) && $_POST['categories'] == "all") { 
$query = "SELECT id, title FROM cars WHERE title LIKE CONCAT(?, '%') ESCAPE '+' ORDER BY id LIMIT ? OFFSET ?"; 
} 
try { 
    $stmt = $db->prepare($query); 
    if(!isset($_POST['search'])) { 
     $stmt->bindValue(1, (int) $limit, PDO::PARAM_INT); 
     $stmt->bindValue(2, (int) $offset, PDO::PARAM_INT); 
    } 
    if(isset($_POST['search']) && $_POST['categories'] != "all") { 
     $search= str_replace(array('+', '%', '_'), array('++', '+%', '+_'), $_POST['search']); 
     $stmt->bindValue(1, $search, PDO::PARAM_STR); 
     $stmt->bindValue(2, (int) $_POST['categories'], PDO::PARAM_INT); 
     $stmt->bindValue(3, (int) $limit, PDO::PARAM_INT); 
     $stmt->bindValue(4, (int) $offset, PDO::PARAM_INT); 
    } 
    if(isset($_POST['search']) && $_POST['categories'] == "all") { 
     $search= str_replace(array('+', '%', '_'), array('++', '+%', '+_'), $_POST['search']); 
     $stmt->bindValue(1, $search, PDO::PARAM_STR); 
     $stmt->bindValue(2, (int) $limit, PDO::PARAM_INT); 
     $stmt->bindValue(3, (int) $offset, PDO::PARAM_INT); 
    } 
    $stmt->execute(); 
} 
catch(PDOException $ex) { 
    die("Failed to run query: " . $ex->getMessage()); 
} 
$cars = $stmt->fetchAll(); 

Mon formulaire de recherche ressemble à ceci:

<input name="search" type="text" size="20" maxlength="20" /> 
<select name="categories"> 
    <option value="all">All Categories</option> 
    <option value="1">Free</option> 
    <option value="2">In use</option> 
    <option value="3">Damaged</option> 
</select> 

Dans le tableau de voitures, chaque ressembler à ceci: 2009 Porsche 911 (année marque modèle) Quand je recherche , si je ne remplis pas dans la boîte de recherche, ça marche bien, ça marche bien même quand je cherche 2009, mais si je cherche Porsche, je n'obtiens aucun résultat. Pourquoi donc? Quel est le problème avec mon code?

+0

Remarque, un raccourci pour 'limite? offset? 'serait' limite?,? '. Je préfère, mais préférence personnelle :) – webnoob

+0

Je voudrais regarder dans le code str_replace. peut-être que vous pouvez var_dump le résultat et obtenir un indice. – Ateszki

Répondre

1

CONCAT(?, '%') signifie que vous recherchez des mots qui commencent par le mot de recherche.

2009 est donc le premier mot pourquoi c'est le retour. si vous voulez obtenir le deuxième mot essayez d'utiliser cette

CONCAT('%',?, '%') 

ou tout simplement comme ça

CONCAT("'",?, "'") 
+0

valeurs de