Reputation: 113
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?
$sql = "SELECT DISTINCT mt.id, mt.name, mt.phone
FROM main_table mt
LEFT JOIN jnct_tbl_srvstate st ON mt.id = st.mt_id
LEFT JOIN jnct_tbl_equip eq on mt.id = eq.mt_id
LEFT JOIN jnct_tbl_accessory ac ON mt.id = ac.mt_id
LEFT JOIN tbl_car c ON mt.id = c.mt_id
WHERE mt.id = c.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)";
}
if($accessory_array_count != 0){
$sql.= " AND accessory_id IN ($ac_holders)";
$sql.= " ORDER BY mt.id";
$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);
Upvotes: 0
Views: 227
Reputation: 562260
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);
$sth->execute();
$result = $sth->fetchAll();
Upvotes: 4