I'm attempting to construct an MySQL query around some optional search parameters in PHP. There are 3 search fields linking to the three columns in my database. The user should be able to search each column individually, or up to all 3 if they want to narrow down their results.
My PHP code is built so that the if one of the search fields is empty, it doesn't matter and it will continue the search in the other two fields. However, I'm struggling to get my head around how to construct my SQL query afterwards as my where
clauses have already been specified in the $whereclauses
array. I am returning the same columns in any search the user makes so that should make the SQL query quite simple and mean it only needs to be defined once.
My PHP code:
<?php
require '../db/connect.php';
$whereclauses = array();
$subsets = false;
// for every field
if(!empty($_POST['name']))
{
$subsets = true;
$whereclauses[] = " ARTIST = ". mysql_real_escape_string(trim($_POST['name']));
}
if($subsets)
{
$whereclauses = implode(", ". $whereclauses);
}
else
{
$whereclauses ="";
}
SQL query in PHP
if(!empty($whereclauses)) {
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3`";
};
$result = mysql_query($sql);
$data = array();
while ($array = mysql_fetch_assoc($result)) {
$data[] = $array;
}
header('Content-type: application/json');
echo json_encode($data);
How can I add the $whereclauses
array into my $sql
query?