user3358839
user3358839

Reputation: 157

how to display number in two digits

I want to select names which expires in this month and two months ahead.

  $t=date('Y');

  $q = date('m');

 for($e=$q;$e<=($q+2);$e++){
 $ren = $t.'-'.$e;
 $sql = "select name,renewal_date from hosting_details where renewal_date LIKE '$ren%' ";

}

In this first month display correctly but then onward doesn't give any result. when i echo $ren,for the first month it gives 2016-01 and second month 2016-2. how can i resolve this

Upvotes: 1

Views: 96

Answers (2)

developerjack
developerjack

Reputation: 1213

You could simply use sprintf() to format the numbers. For example:

$t=date('Y');
$q = date('m');

for($e=$q;$e<=($q+2);$e++){
  $ren = $t.'-'. sprintf("%'.02d", $e);
  var_dump($ren);
}

More info on sprintf() can be found in the docs.

However since you're working with dates, why not use a \DateTime object and have it do the work for you? This means you don't have to do any date overflow logic etc - PHP does all the complex work for you! :) e.g.

$begin = new DateTime( '2016-01-11' );
$numMonths = 2;
for($i=0; $i<$numMonths; $i++)
{
    // e.g. increment the month and format the date.
    var_dump($begin->modify( '+1 month' )->format("Y-m-d"));

    // of course modify the format to "Y-m" for your code:
    // $ren = $begin->modify( '+1 month')->format("Y-m");
}

For more reading you can checkout \DateTime and \DatePeriod in the PHP docs.

Here's a working example comparing the two approaches.

Upvotes: 1

maxhb
maxhb

Reputation: 8845

Using sprintf() can solve your problem:

$t=date('Y');
$q = date('m');

for($e=$q;$e<=($q+2);$e++){
  $ren = sprintf('%d-%02d', $t,$e);
  $sql = "select name,renewal_date from hosting_details where renewal_date LIKE '$ren%' ";
  echo $sql . "\n";
}

Output:

select name,renewal_date from hosting_details where renewal_date LIKE '2016-01%' 
select name,renewal_date from hosting_details where renewal_date LIKE '2016-02%' 
select name,renewal_date from hosting_details where renewal_date LIKE '2016-03%' 

Upvotes: 0

Related Questions