Reputation: 885
Hello I would like to know how I can transform the following code to use BindValues and to do the same job.
$sql = "SELECT * FROM documents WHERE 1";
if (!empty($topic)) {
$sql .= " AND topic = '$topic' ";
}
if (!empty($date )) {
$sql .= " AND date LIKE '%$date%' ";
}
WHERE clause to be applied only on the filled input So my question is how to transform this code in to the the following query
$sql = new page($pages "SELECT *
FROM table
WHERE topic LIKE :topic
OR date LIKE :date ", $option);
$sql ->BindValue(':topic ', $_POST['topic '], PDO::PARAM_STR);
$sql ->BindValue(':date ', $_POST['date '], PDO::PARAM_STR);
Upvotes: 2
Views: 348
Reputation: 41810
There is more than one way to do it, but one way would be to keep using the same logic you're already using to add the optional conditions, and then use it again to optionally bind the values.
$sql = "SELECT * FROM documents WHERE 1";
// add the conditions with the placeholders
if (!empty($topic)) { $sql .= " AND topic LIKE :topic"; }
if (!empty($date)) { $sql .= " AND date LIKE :date"; }
// bind the values
if (!empty($topic)) { $sql ->BindValue(':topic', '%'.$_POST['topic'].'%', PDO::PARAM_STR); }
if (!empty($date)) { $sql ->BindValue(':date', '%'.$_POST['date'].'%', PDO::PARAM_STR); }
Upvotes: 2
Reputation: 204756
SELECT * FROM table
WHERE (:topic is null or topic LIKE :topic)
AND (:date is null or date LIKE :date)
Upvotes: 0