Skip to content
Advertisement

How to set conditions for search in prepared statements?

I am trying to create a site search in prepared statements,

Here is my code : Conditions for search

$whereSQL = $orderSQL = ''; 
if(!empty($_POST['keywords'])){ 
    $whereSQL = "WHERE title LIKE '%".$_POST['keywords']."%'"; 
} 
if(!empty($_POST['sortBy'])){ 
    $orderSQL = " ORDER BY title ".$_POST['sortBy']; 
}else{ 
    $orderSQL = " ORDER BY title DESC "; 
} 

This is how I add it to query :

$stmt = $pdo->prepare("SELECT * FROM posts ".$whereSQL.$orderSQL); 
$stmt->execute(); 
$rowCount= $stmt->rowCount(); 

Here is my question. How can I use conditions safe way in prepared statements ?

Advertisement

Answer

You can build up an array of any bind parameters dynamically and then pass this to the execute()

As the only value you can bind is in the WHERE clause, you only need to alter than part…

$whereSQL = $orderSQL = ''; 
$bindParams = [];
if(!empty($_POST['keywords'])){ 
    $whereSQL = "WHERE title LIKE :title"; 
    $bindParams['title'] = '%'.$_POST['keywords'].'%';
} 

$stmt = $pdo->prepare("SELECT * FROM posts ".$whereSQL.$orderSQL); 
// Pass values to statement
$stmt->execute($bindParams); 
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement