2
  $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?

1 Answer 1

3

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
]);
Sign up to request clarification or add additional context in comments.

1 Comment

Outstanding answer! You figured out what the questioner was trying to do, and gave him (and us all) the conceptual framework to get it right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.