Tomazi
Tomazi

Reputation: 781

php compare current date with dates stored in database

I am trying coding a php script where i want to extract a date field from a database table,store this date compare it with todays. To see if the data. from database has passed or not compared to todays date.

  1. the code i have written for this functionality looks like its not working
  2. I think i am getting the date() format wrong.
  3. I am not to sure about the logic if statments.

php

$sql="SELECT enddate FROM campaigns WHERE id=".$data['camp'];
    $result = mysqli_query($db, $sql);

while($info = mysqli_fetch_assoc($result)){
    if(date("Y-m-d") > $result){
        exit;
        echo "Success";
    }
    elseif(date("Y-m-d") < $result){
        return true;
        echo "Failure";
    }
}

Upvotes: 1

Views: 16485

Answers (5)

Kishan
Kishan

Reputation: 1190

I spend lot of time to compare only dates and i found a solution like this

Always set format like date('Y-m-d')

$dateTo='2016-08-07';
if(date("Y-m-d", strtotime($dateTo)) > date('Y-m-d')){
   echo 'yes';
}else{
   echo 'no';
}

Upvotes: 0

flicher88
flicher88

Reputation: 35

You can use below query :

$sql="SELECT (CASE WHEN DATE(NOW()) > enddate THEN 'success' ELSE 'failed' END) AS mystatus FROM campaigns WHERE id=".$data['camp'];

Then you just need to call mystatus column from the query.

Upvotes: 0

kba
kba

Reputation: 19466

Youl could just let MySQL worry about it.

SELECT DATEDIFF(NOW(),enddate) FROM campaigns WHERE id=".$data['camp']

That will return the number of days between the two dates. See the manual for DATEDIFF.

Upvotes: 1

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

Use strtotime()

while($info = mysqli_fetch_assoc($result)){
    if(strtotime(date("Y-m-d")) > strtotime($result)){
        exit;
        echo "Success";
    }
    elseif(strtotime(date("Y-m-d")) < strtotime($result)){
        return true;
        echo "Failure";
    }
}

Upvotes: 2

Ramesh
Ramesh

Reputation: 4293

You have to do:

if(date("Y-m-d") > $info['enddate']) {

Upvotes: 1

Related Questions