doejos
doejos

Reputation: 23

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in you

  $wordsAry = explode(" ", $search);
$wordsCount = count($wordsAry);
$queryCondition = " WHERE ";
for($i=0;$i<$wordsCount;$i++) {
    $queryCondition .= "`location` LIKE '%$wordsAry[$i]%'";
    if($i!=$wordsCount-1) {
        $queryCondition .= " OR ";
    }
}
echo $queryCondition;

$sql1 = "SELECT * FROM `shelves_instruments` 
:szukaj
ORDER BY location ASC";
$licz_ilosc = $connect_db -> prepare($sql1);
$licz_ilosc -> bindValue(':szukaj', $queryCondition, PDO::PARAM_STR);
$licz_ilosc -> execute(); 
$ilosc_stron = $licz_ilosc->rowCount();

WHERE location LIKE '%walida%'

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' WHERE location LIKE '%walida%'' ORDER BY location ASC' at line 2 in

What could be wrong?

Upvotes: 2

Views: 4024

Answers (1)

Prepared statements aren't a fancy way of substituting text. You can't send an entire WHERE clause as a single parameter.

You need to create a WHERE clause like this:

$where = "WHERE `location` like :term1 OR `location` like :term2";

Then create your terms such that

     $param1 = '%'.$firstTerm.'%'  ;
     $param2 = '%'.$secondTerm.'%'  ;

Then bind your terms to your prepared statement

$query = "SELECT * FROM `shelves_instruments` ".$where." ORDER BY location ASC"
$licz_ilosc = $connect_db -> prepare($query);
$licz_ilosc->execute([
    "term1"=>$param1,
    "term2"=>$param2
]);

Upvotes: 3

Related Questions