Reputation: 785
I'm struggline with something that i feel should be really simple, and i wonder if any of you can help.
Long story short; in my php search form, a user can pick a 'fromdate' and a 'todate'. They can also enter two strings, which are generally phone numbers.
The user doesnt have to enter a date range, they can just search using sender and receiver. If this is the case, I want the $daterange_stmt to be blank and the AND operator to not be present in the SQL statement.
Similarly if the user only provides a date range and not a sender/receiver, I want the SQL statement to not contain the AND operator and not contain the $operator_stmt.
Please excuse me if some of this code is nonsense - I've added and changed bits all over the place trying to get this working... php isn't my strong point.
Vars are grabbed like this...
$df = $_POST['df'];
$dt = $_POST['dt'];
$sender = $_POST['sender'];
$reciever = $_POST['reciever'];
My SQL select statement looks like this...
$sql = "SELECT * FROM comms_session_all s JOIN operators u ON s.agent = u.user_id WHERE " . $whereclause . " ORDER BY start_time ASC";
$Whereclause is declared like so...
$daterange_stmt = "";
$operator_stmt= "";
if(!($df==" ")){
$daterange_stmt = "start_time between '" . $df. "' AND '" . $dt. "'";
}
if(!(empty($sender))){
$operator_stmt= "sender like '%" . $sender . "%' AND reciever like '%" . $reciever. "%'";
}
$whereclause = $daterange_stmt;
if(!(df==" ")){
if(!($operator_stmt=="")){
$whereclause = $daterange_stmt . " AND " . $operator_stmt;
}
} else {
if(!($operator_stmt=="")){
$whereclause = $operator_stmt;
}
}
So currently if a date range is supplied and the sender/receiver are supplied then the search works and all is good.
If only one of the bits is entered, it fails because of a rogue AND that needs to not be there. The SQL statement when executed comes out as this...
SELECT * FROM comms_session_all s JOIN operators u ON s.agent = u.user_id WHERE AND sender like '%447958xxxx%' AND receiver like '%123456%' ORDER BY start_time ASC2
Any help at all is appriciated! thanks in advance
Upvotes: 0
Views: 17