Skip to content
Advertisement

PHP If/Else Statements Not Hitting All Cases

I have this as my syntax, and my issue is that if both $employee and $saleDate are set the where clause is added as expected. However, if only $employee OR $saleDate are set, then the where clause is never added to the query.

What is the proper way to write this syntax so that the appropriate where clauses is added based off the user selection?

if (!is_null($employee) && !is_null($saleDate)) {
  if (!empty($employee) && !empty($saleDate)) {
    $sql2 .= " where employee = '$employee' AND saleDate = '$saleDate'";
  }  
}

elseif(!is_null($date)) {
if (!empty($date)) {
    $sql2 .= " where saleDate = '$saleDate'";
  }
}

elseif (!is_null($employee)) {
  $sql2 .= " where employee = '$employee'";
}

EDIT
My syntax here is working, except for where employee = ALL it is somehow missing that (or ignoring that since I thought I accounted for that)

$date = $_POST['userSelectedDate'];
$employee = $_POST['empName'];
if (!is_null($employee) && !is_null($saleDate)) {
if (!empty($employee) && !empty($saleDate)) {
if ($employee <> 'All') {
$sql .= " where employee = '$employee' and salesaleDate = '$saleDate'";
}
}
}

if(!is_null($employee)) {
$sql .= " where employee = '$employee'";
}

if(!is_null($saleDate)) {
if (!empty($saleDate)) {
$sql .= " where salesaleDate = '$saleDate'";
}
}

Advertisement

Answer

The whole script can be simplified into the following one:

$saleDate = $_POST['userSelectedDate'];
$employee = $_POST['empName'];

$conditions = [];

if (!empty($employee) && strtolower($employee) !== 'all') {
    $conditions[] = "employee='$employee'";
}

if (!empty($saleDate)) {
    $conditions[] = "saleDate='$saleDate'";
}

if (!empty($conditions)) {
    $sql .= ' WHERE ' . implode(' AND ', $conditions);
}

BUT, please note that your query is prone to SQL injection, so you better use prepared statements.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement