I'm trying to combine a search bar with checkboxes for a query in PDO.
The current code is like this:
$keywordfromform = $_GET["keyword"];
$keyword = "%$keywordfromform%";
$sql = 'SELECT * FROM table
WHERE column1 LIKE ?
OR column2 LIKE ?
OR column3 LIKE ?
ORDER BY column3 ASC';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($keyword, $keyword, $keyword);
$entries = $stmt->fetchAll();
$count = count($entries);
With the same logic, I tried to apply implode and the in-clause as follows (according to this site ):
//search bar
$keywordfromform = $_GET["keyword"];
$keyword = "%$keywordfromform%";
//checkboxes
$column1 = $_GET['checkboxes_column1'];
$implode_column1 = implode(', ', $column1);
$in str_repeat('?,', count($implode_column1) - 1) . '?';
$sql = 'SELECT * FROM table
WHERE column1 LIKE ?
OR column2 LIKE ?
OR column3 LIKE ?
AND column1 IN ($in)
ORDER BY column3 ASC';
$stmt = $pdo->prepare($sql);
$params = array_merge([$keyword], [$keyword], [$keyword], $implode_column1);
$stmt->execute($params);
$entries = $stmt->fetchAll();
$count = count($entries);
The search bar and checkboxes are standard ones from bootstrap, nothing special.
Maybe someone could kindly point out what I'm doing wrong?
$sql
uses single quotes not double; therefore $in
is literal
count($implode_column1)
isn't countable; it's a string
$in str_repeat(...)
- as per the comments - needs an assignment operator
array_merge(...)
doesn't work; $implode_column1
is a string
Assumption you need parenthesis to specify order of operation assuming that the ORs
should be grouped together:
(a =... OR b =... OR c =...) AND a IN (...)
Assuming that your incoming data is in the format:
$_GET['keyword'] = "html";
$_GET['checkboxes_column1'] = [
0 => "php",
1 => "css",
2 => "js",
3 => "html"
];
$keyword = $_GET['keyword'] ?? NULL;
$column1 = $_GET['checkboxes_column1'] ?? NULL;
// Check that the expected data was received
if(!$column1 || !$keyword || !is_array($column1)){
echo "Error: Nothing submitted";
exit;
}
$keyword = "%{$keyword}%";
$placeholders = implode(", ", array_fill(0, count($column1), "?")); // Prepare placeholder string
$parameters = array_merge([$keyword, $keyword, $keyword], $column1); // Prepare array for variables to bind
$sql = "
SELECT * FROM table
WHERE (
column1 LIKE ?
OR column2 LIKE ?
OR column3 LIKE ?
) AND column1 IN ({$placeholders})
ORDER BY column3 ASC
";
$query = $pdo->prepare($sql);
$query->execute($parameters);
$result = $query->fetchAll();
$count = count($result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.