I have a script that will query my database and needs to be able to query using one or all of four options. The options are start sku, end sku (this is one option as there has to be a range to search), created by and date created. I know I can do this using MANY if..elseif statements, but I have to think there is a better and easier way. Here is what I have for code so far:
$start =mysql_real_escape_string ($_POST['skuStart']);
$end = mysql_real_escape_string($_POST['skuEnd']);
$source = mysql_real_escape_string($_POST['source']);
$processDate = mysql_real_escape_string($_POST['processDate']);
if(!empty($start) && !empty($end) && empty($source) && empty($processDate)){
$result = $conn->query("Select * from inventory where sku >= $start and sku <= $end");
} elseif (empty($start) && empty($end) && !empty($source) && empty($processDate)){
$result = $conn->query("Select * from inventory where created_by = '$source'");
} elseif (empty($start) && empty($end) && empty($source) && !empty($processDate)) {
$result = $conn->query("Select * from inventory where date_process = '$processDate'");
} elseif(!empty($start) && !empty($end) && !empty($source) && empty($processDate)){
$result = $conn->query("Select * from inventory where sku >= $start and sku <= $end and created_by = '$source'");
} else {
$result = $conn->query("Select * from inventory where sku >= '$start' and sku <= '$end' and created_by = '$source' and date_process = '$processDate'");
}
while($row = $result->fetch_assoc())
{
$skuArray[$x] = $row['sku'];
$isbnArray[$x] = $row['isbn13'];
$qtyArray[$x] = $row['quantity'];
$defectArray[$x] = $row['defect_id'];
$sourceArray[$x] = $row['source_id'];
$featureArray[$x] = $row['feature_id'];
$locationArray[$x] = $row['location_id'];
$processDateArray[$x] = $row['date_process'];
$bookTypeArray[$x] = $row['book_type_id'];
$createdByArray[$x] = $row['created_by'];
$modifiedByArray[$x] = $row['modified_by'];
$x++;
This very crude form is working, but is there a way to get the if elseif simplified?
NOTE: I know that I should be using PDO to prevent sql injection, but I have not fully learned that yet, so I am using this.
Setting aside the issues you’re already aware of – switching to PDO and using bound parameters – You could make your code a little clearer with the following: