cleft cleft - 1 month ago 4x
MySQL Question

PDO MySQL prepared statement with optional where statements

I am working on a query that is submitted from a form with a variety of search options that could or could not be included in my query. Is there a better way to do this dynamically as this doesn't seem to work?

I keep getting error

Fatal error: Call to a member function fetchAll() on boolean
. I know there is a lot going on here and I didn't want to put a ton of code to read through. So to make a long story short, when I echo out $sql my select statement looks good, but no matter what I do I keep getting the same error which tells me there is something wrong with the statement. Is this approach even workable or do I need to use another method? If so what is a better approach?

FROM main_table mt
LEFT JOIN jnct_tbl_srvstate st ON = st.mt_id
LEFT JOIN jnct_tbl_equip eq on = eq.mt_id
LEFT JOIN jnct_tbl_accessory ac ON = ac.mt_id
LEFT JOIN tbl_car c ON = c.mt_id

if($state_array_count != 0){
$sql.= " AND srvstate_id IN ($st_holders)";
if($equip_array_count != 0){
$sql.= " AND equip_id IN ($eq_holders)";
$sql.= " AND equip_id IN (1, 2)";
if($accessory_array_count != 0){
$sql.= " AND accessory_id IN ($ac_holders)";

$sql.= " ORDER BY";

$query = $db->prepare($sql);

Incorporating the if statements above is what I really need help with.

if($state_array_count != 0){
foreach($state_array as $st_placeholder => $st_value) {
if($st_value != '') {
$st_placeholder = ":$st_placeholder";
$query->bindValue($st_placeholder, $st_value);

if($equip_array_count != 0){
if($eq_value != '') {
foreach($equip_array as $eq_placeholder => $eq_value) {
$eq_placeholder = ":$eq_placeholder";
$query->bindValue($eq_placeholder, $eq_value);

if($accessory_array_count != 0){
foreach($accessory_array as $ac_placeholder => $ac_value) {
if($ac_value != '') {
$ac_placeholder = ":$ac_placeholder";
$query->bindValue($ac_placeholder, $ac_value);

$results = $query->execute();

$rs = $results->fetchAll(PDO::FETCH_ASSOC);


The execute() method does not return a results object. It returns a boolean, true or false.

fetchAll() is a method of the PDOStatement object. Here's an example:

$sth = $dbh->prepare($sql);
$result = $sth->fetchAll();