Is there a simpler way for me to code this and perform the same thing without having to have so many queries? Im trying to add pagination (not included in code here) and it work
My thought is to iterate the $_POST array and bind only the variables you need.
You are misunderstanding the use of AND and OR. If only one of the two is selected, you don't need to OR on the second one!
$value) {
$where_clauses[] = "$param = :$param";
}
$where_clauses = implode(" AND ", $where_clauses);
$query .= $where_clauses;
}
$stmt = $pdo->prepare($query);
foreach ($parameters as $param => $value) {
$stmt->bindValue(":$param", $value);
}
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
try {
$db = new PDO("mysql:host=localhost;dbname=database_name", "user", "password");
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
select_product($db, $_POST);
}
catch (PDOException $e) {
die("Database problem occurred! " . $e->getMessage());
}
The code will not work for you as is, so don't copy/paste it right away.
This function assumes that the form names match the database names, and will act accordingly. If your column name is module_type, name the form field which matches it module_type as well.
The advantages of such code, is that you can add more columns and more filters, and you won't have to change a single line of code :)