user1449596
user1449596

Reputation: 309

issue with if condition for variable

I have two parameters in my stored procedure i.e. @startdate and @enddate. The user selects startdate from text box and enddate also from text box. Then click submit.

I want to make sure if user leaves blank both the boxes, it should display data for the whole current month i.e. 01/08/2012 to 31/08/2012 now.

If user just selects date in any one of the boxes, the other text box should have the same value.

So I have declared variable as below and tried the condition but it always display data for whole month irrespective of what date is selected. I think there is a problem with my if condition.

$startdate = isset($_REQUEST['startdate']) ? $_REQUEST['startdate'] : null;
$enddate   = isset($_REQUEST['enddate']) ? $_REQUEST['enddate'] : null;
if (empty($startdate)) {
    $startdate = $enddate;
}
if (empty($enddate)) {
    $enddate   = $startdate;
}
if (empty($startdate))
    ;
if (empty($enddate))
    ;
$startdate = '01/08/2012';
$enddate   = '31/08/2012';

Upvotes: 0

Views: 96

Answers (3)

fdomig
fdomig

Reputation: 4457

The last two if statements have no influence of the program flow. You always set $startdate and $enddate to the specified dates.

You need:

if(empty($startdate)) $startdate = '01/08/2012';
if(empty($enddate)) $enddate = '31/08/2012';

If you want to get the first and last day of the actual month every time you could use something like this:

if(empty($startdate)) $startdate = date('01/m/Y', strtotime("-1 month"));
if(empty($enddate)) $enddate = date('d/m/Y', strtotime("-1 month"));

Upvotes: 4

Kermit
Kermit

Reputation: 34063

The logic was not correct. This should work.

$startdate = isset($_REQUEST['startdate']) ? $_REQUEST['startdate'] : null;
$enddate = isset($_REQUEST['enddate']) ? $_REQUEST['enddate'] : null;

if (empty($startdate)) {
$startdate  = $enddate ;
}
elseif (empty($enddate)) {
$enddate = $startdate;
}
elseif(empty($startdate) && empty($enddate)) {
$startdate = '01/08/2012';
$enddate = '31/08/2012';
}

Upvotes: 1

andrewsi
andrewsi

Reputation: 10732

I think this will work

$startdate = isset($_REQUEST['startdate']) ? $_REQUEST['startdate'] : "";
$enddate = isset($_REQUEST['enddate']) ? $_REQUEST['enddate'] : "";

if (empty($startdate) && (empty($enddate)) {
    $startdate = '01/08/2012';
    $enddate = '31/08/2012';
} elseif (empty($startdate) {
    $startdate = $enddate;
} elseif (empty($enddate) {
    $enddate = $startdate;
}

If both are empty, it uses the start and end of this month; if one or the other is empty, it uses the value for the other.

Upvotes: 1

Related Questions