How to use prepare for query having LIKE clause

时间:2018-04-18 17:54:30

标签: php pdo

Please see the below code. This works fine with mysqli method, but is prone to sql injection. So I want to use prepared statements, but for LIKE I cant use it.

$t = strtolower($_POST['e']);
$search_exploded = explode(" ", $t);
$construct = '';
foreach ($search_exploded as $search_each) {
    $construct .= "AND title LIKE ? ";
}

$query = $conn->prepare("SELECT * FROM vdo WHERE 1 $construct ");
$query->execute(["%$search_each%"]);
$found = $query->rowCount();
if ($found == 0) {
    echo "NO Result Found";

} else {
    while ($row_id1 = $query->fetch(PDO::FETCH_ASSOC)) {
        echo $title = $row_id1['title'];
    }  
}

1 个答案:

答案 0 :(得分:1)

You're only passing one parameter, the last of the array of search terms from your foreach loop.

$query->execute(["%$search_each%"]);

You need to use the entire array of terms instead.

$params = array_map(function($term) { return "%$term%"; }, $search_exploded);
$query->execute($params);