I am converting all my queries from mysql to PDO, and in this process I found a conditional query like a follows
if (isset($parameters['searchTerm'])) {
$where =" And title LIKE '%{$parameters['searchTerm'] }%'";
}
$sql = "Select * from table data Where tableId = 5 {$where} ";
and when I am trying to convert this query in PDO the expected syntax is as follows
if (isset($parameters['searchTerm'])) {
$where =" And title LIKE :searchTerm";
}
$sql = $dbh->prepare("Select * from table data Where tableId = 5 {$where}");
if (isset($parameters['searchTerm'])) {
$sql ->bindParam(':searchTerm', '%{$parameters['searchTerm'] }%');
}
$sql ->execute();
Now as you can See that the if condition if (isset ($parameters ['searchTerm'] )) {...}
is repeated twice.
The reason is
So there is one if statement before $sql = $dbh->prepare("Select * from table data Where tableId = 5 {$where}");
and one if statement after.
And my question is: Is there a way to remove this redundant if statement or I have to do it this way only.
You can use a handy PDO's feature that allows you to send array with parameters straight into execute()
$where = '';
$params = array();
if (isset($parameters['searchTerm'])) {
$where = " And title LIKE :searchTerm";
$params['searchTerm'] = "%$parameters[searchTerm]%";
}
$sql = "Select * from table data Where tableId = 5 $where";
$stmt = $pdo->prepare($sql)
$stmt->execute($params);
$data = $stmt->fetchAll();