Search code examples
phpmysqlisset

php !isset and empty not working


Pulling my hair out on this, it has to be obvious, but I can't see it today.

I built a small monitoring tool for an app we have. I want to do a check in the DB to make sure the backend scripts are working and the data isn't stale by more than 15 min. When no records are returned in a certain timeframe it should pop up a message saying to check the script. If they are not returned it should be an empty dataset and I should get a message on it.

Problem is, I can't get empty() or !isset to work. Actually regardless of whether I use !empty(), empty(), isset() or !isset(), my $tripped variable never gets tripped. I have this working for other alerts, but this one seems to be stubborn and I don't see what I'm missing.

PS I know mysql_ is out of date.

The relevant piece of code:

    $ldap_check = mysql_query("SELECT 
*
 FROM ldap_conns
 WHERE DATETIME > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
order by DATETIME DESC
LIMIT 1");


while($row = mysql_fetch_array($ldap_check))

  {
        if (empty($row['DATETIME']))
            {
            echo '<b><font color=blue><a href="server_check.php">Stale Data</a>: </font> <font color=red>LDAP data is old, check script!</font><br>' . $row['DATETIME'];
            $tripped='Yes';
            }
  }

            if ($tripped!='Yes')
            {
                echo '<a href="server_check.php"><b><font color=blue>Stale Data</a>: ' . $row['DATETIME'] . '</font></b> <font color=green> No Problems Found<br></font>';
            } 

Solution

  • You are doing it wrong... Want just check if there exists any old items? Use count! There is no reason for selectin g ALL fields from ALL records from the table. This is wrong using of database! Use count, and make index on DATETIME field!

    $result = mysql_query("SELECT 
        count(*) old_items
    FROM
        ldap_conns
    WHERE
        DATETIME < DATE_SUB(NOW(), INTERVAL 15 MINUTE)");
    
    $row = mysql_fetch_row($result);
    
    if ($row['old_items']) {
       echo 'There is '.$row['old_items'].' old items!';
    }