I'm trying to find matches in MySQL database using PHP loops to build the query:
public function findMatches(array $columns, string|array $lookingFor) {
is_array($lookingFor) ?: $lookingFor = array($lookingFor);
$colString = '';
$whereString = '';
$toBind = [];
foreach ($columns as $col) {
$colString .= $col . ',';
foreach ($lookingFor as $item) {
$whereString .= $col . " LIKE '%?%' OR ";
$toBind[] = $item;
}
}
$sql = 'SELECT ' . rtrim($colString, ',') . ' FROM ' . $this->table .
' WHERE ' . rtrim($whereString, ' OR ');
$stmt = $this->dbc->prepare($sql);
$pos = 1;
foreach ($toBind as $val) {
$stmt->bindValue($pos, $val);
$pos++;
}
$stmt->execute();
return $stmt->fetchAll();
}
The $toBind
values count is exactly same as iterations of the bind loop, so I'm not sure what I did wrong. I would appreciate help to solve following error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens