I'm combining my MySQL queries so the user can select multiple dropdowns and filter based on those dropdowns. This works as intended as I've checked using $echo query. However, I need to insert an "AND " before each occurence of the word "WHERE" except for the first one. At the moment my query comes out like this if I select multiple drodowns:
SELECT a.MembershipID,
a.FirstName,
a.Surname,
t.RaceID,
t.Time,
r.RaceID,
r.RaceName,
r.Distance,
r.ClubYear
FROM Athlete AS a
INNER JOIN Time AS t ON a.MembershipID=t.MembershipID
INNER JOIN Race AS r ON t.RaceID=r.RaceID
WHERE r.RaceName= 'Parkrun' WHERE r.Distance= '5 kilometres'
ORDER BY a.Surname
As you can see on line 4, there are two WHERE queries with no AND. How can I insert an AND before the second WHERE? How can I do this for every subsequent WHERE except the first? I thought about using explode to create substrings, insert the AND and then join them back together, but this seems a little over the top. Any help? Thanks.
Edit: Add PHP code that generates the above:
$query = "SELECT a.MembershipID, a.FirstName, a.Surname, t.RaceID, t.Time, r.RaceID, r.RaceName, r.Distance, r.ClubYear
FROM Athlete AS a
INNER JOIN Time AS t
ON a.MembershipID=t.MembershipID
INNER JOIN Race AS r
ON t.RaceID=r.RaceID";
if ($_POST['raceName']!= null) {
$raceName = mysqli_real_escape_string($mysqli, $_POST["raceName"]);
$filter = " WHERE r.RaceName= '$raceName'";
$query .= $filter;
}
if ($_POST['athlete']!= null) {
$athlete = mysqli_real_escape_string($mysqli, $_POST["athlete"]);
$firstWord = explode(' ',trim($athlete));
$firstName = $firstWord[0];
$lastWord = explode(' ', $athlete);
$surname = array_pop($lastWord);
$filter = " WHERE a.FirstName= '$firstName' AND a.Surname = '$surname'";
$query .= $filter;
}
if ($_POST['distance']!= null) {
$distance = mysqli_real_escape_string($mysqli, $_POST["distance"]);
$filter = " WHERE r.Distance= '$distance'";
$query .= $filter;
}
if ($_POST['clubYear']!= null) {
$clubYear = mysqli_real_escape_string($mysqli, $_POST["clubYear"]);
$filter = " WHERE r.ClubYear= '$clubYear'";
$query .= $filter;
}
$fullquery = $query . " ORDER BY a.Surname";
WHEREwithANDand not append theENDbefore it, as that would create anAND WHEREwhich is not valid