I was using and if statement to append $query .= "AND column LIKE $suchandsuch" in my search engine when I had it set up with mysqli, but I'm updating it to PDO and am struggling to figure out how to make sure it will ignore the fields that are left blank.
The form fields are: condition, degree, specialty, city, state. Condition is required, but nothing else is, so it needs to ignore those fields when they're empty. I feel like this should be obvious but I'm new to PDO and stumped.
if(isset($_POST['submit'])){
$condition = $_GET["condition"];
if(isset($_GET["degree"]) && !empty($_GET["degree"])){
$degree = $_GET["degree"];
}
if(isset($_GET["specialty"]) && !empty($_GET["specialty"])){
$specialty = $_GET["specialty"];
}
if(isset($_GET["city"]) && !empty($_GET["city"])){
$city = $_GET["city"];
}
if(isset($_GET["state"]) && !empty($_GET["state"])){
$state = $_GET["state"];
}
$query = $connection->prepare("SELECT
`providers`.`provider_first_name`, `providers`.`provider_last_name`,
`providers`.`p_date_added`, `providers`.`id`,
(SELECT GROUP_CONCAT(DISTINCT `degree_type` SEPARATOR ', ')
FROM `degrees`
WHERE `providers`.`id` = `prov_id`
) AS all_degrees,
(SELECT GROUP_CONCAT(DISTINCT `specialty` SEPARATOR ', ')
FROM `specialties`
WHERE `providers`.`id` = `prov_id`
) AS all_specialties,
(SELECT GROUP_CONCAT(DISTINCT CONCAT(`locations`.`city`, ', ',
`locations`.`state`)
SEPARATOR '<br>')
FROM `locations`
WHERE `providers`.`id` = `prov_id`
) AS all_locations,
(SELECT GROUP_CONCAT(DISTINCT `practice_name` SEPARATOR ', ')
FROM `practices`
WHERE `providers`.`id` = `prov_id`
) AS all_practices,
(SELECT GROUP_CONCAT(DISTINCT `link` SEPARATOR '<br>')
FROM `links`
WHERE `providers`.`id` = `prov_id`
) AS all_links,
(SELECT GROUP_CONCAT(DISTINCT `condition_name` SEPARATOR ', ')
FROM `conditions`
WHERE `providers`.`id` = `prov_id`
) AS all_conditions,
(SELECT AVG(`reviews`.`star_rating`)
FROM `reviews`
WHERE `providers`.`id` = `prov_id`
) AS rating
FROM `providers`
WHERE `all_conditions` LIKE :condition");
if($degree && !empty($degree)){
$query.= " AND (`all_degrees` LIKE :degree)";
$degree = "%".$degree."%";
$query->bindParam(':degree', $degree, PDO::PARAM_STR);
}
if($specialty && !empty($specialty)){
$query.= " AND (`all_specialties` LIKE :specialty)";
$specialty = "%".$specialty."%";
$query->bindParam(':specialty', $specialty, PDO::PARAM_STR);
}
if($city && !empty($city)){
$query .= " AND (`all_locations` LIKE :city)";
$city = "%".$city."%";
$query->bindParam(':city', $city, PDO::PARAM_STR);
}
if($state && !empty($state)){
$query .= " AND (`all_locations` LIKE :state)";
$state = "%".$state."%";
$query->bindParam(':state', $state, PDO::PARAM_STR);
}
$condition = "%".$condition."%";
$query->bindParam(':condition', $condition, PDO::PARAM_STR);
$query->execute();