2017-01-17 5 views
1

Ich versuche, eine Suche in PHP mit PDO zu erstellen. Es hat zwei Eingabefelder. Derzeit Wenn ich eines der Felder und den zugehörigen PHP-Code entferne, ruft es die Daten aus der Datenbank ab. Wenn beide vorhanden sind, beschränkt der Inhalt des Felds "Witz" die Daten nur, wenn die Eingabe "Autor" vorhanden ist.PHP PDO mehrspaltige Suche

dies ist der HTML:

<div> 
    <form action="search.php" method="get"> 
     <label for="text">Joke</label> 
     <input type="text" name="text" id="text"> 

     <label>Author</label> 
     <label for="author">author</label> 
     <select name="author" id="author"> 
      <option>select</option> 
      <option value="1">1</option> 
      <option value="2">2</option> 
     </select> 

     <button type="submit" class="btn btn-orange">Go</button> 
    </form> 
</div> 

ist dies die PHP:

<?php  
    $query = "SELECT * FROM joke WHERE TRUE"; 
    $bind = Array(); 

    if ($_GET) 
    { 
     if ($_GET["text"] && $_GET["text"] != "") { 
      $query .= " and joke_text like :joke_text"; 
      $bind[':joke_text'] = "%{$_GET['text']}%"; 
     } 

     if ($_GET["author"] && $_GET["author"] != "") { 
     $query .= " and author_id = :author_id"; 
      $bind[':author_id'] = "{$_GET['author']}"; 
     } 

     $stmt = $dbConnection->prepare($query); 
     $stmt->execute($bind); 
     $rows = $stmt->fetchAll(); 

     var_dump($rows); 
    } 
?> 

ich keine Fehlermeldungen erhalten, die vorhanden sind.

Könnte jemand bitte einen Blick darauf werfen?

+0

Was '$ dbConnection-> errorInfo()' zurückgibt? – marian0

+0

AFAIK sollte es sein $ bind ['joke_text'] 'anstelle von $ bind [': joke_text']' –

+0

Also wenn es nicht funktioniert, was ist die var_dump (oder print_r) von $ _GET? – MacPrawn

Antwort

0

Das beste Muster hier ist eine Liste von Bedingungen zu sammeln und sie mit implode kollabieren, wenn Sie fertig:

$bind = [ ]; 
$conds = [ ]; 

if ($_GET) 
{ 
    if ($_GET["text"] && $_GET["text"] != "") { 
     $conds[] = "joke_text like :joke_text"; 
     $bind[':joke_text'] = "%{$_GET['text']}%"; 
    } 

    if ($_GET["author"] && $_GET["author"] != "") { 
     $conds[] = "author_id = :author_id"; 
     $bind[':author_id'] = "{$_GET['author']}"; 
    } 

    $stmt = $dbConnection->prepare($query . ($conds ? " WHERE " . implode(" AND ", $conds) : ""); 
    $stmt->execute($bind); 
    $rows = $stmt->fetchAll(); 

    var_dump($rows); 
} 

diese Weise die WHERE Klausel wird nur angezeigt, wenn es etwas Wichtiges zu tun und die AND Aussagen sind nur eingeführt Falls benötigt.