PHP / mySQL获得x秒的时差

My goal is to get the time difference between 2 different times, one from my database, and one from the client's PHP timestamp, and compare them. Then, if the time difference is less than or equal to 10 seconds, then do something.

My code, which does not work, is as follows.

date_default_timezone_set('America/Chicago');
$timestamp = date('Y-m-d H:i:s');

$sqlcheck = $dbh->prepare("SELECT timestem FROM mytable WHERE UNIX_TIMESTAMP(timestem) - UNIX_TIMESTAMP('".$timestamp."') <= 10");
$sqlcheck->execute();
    if ($sqlcheck === ''){
        echo "Yes";
    }
    else {
        echo "No";
    } 

timestem is a DATETIME value from mySQL. $sqlcheck is meant to portray the result of the query. If the query returns nothing, then echo Yes. If it returns something from my query, then echo No.

Without getting too convoluted in explanation, my end-goal is to check how long it has been since a database operation before a client is allowed to perform updates.

You should use the MySQL built-in TIMESTAMPDIFF function:

$sqlcheck = $dbh->prepare('SELECT timestem FROM mytable WHERE TIMESTAMPDIFF(SECOND, timestem, $1) <= 10');
$result = $sqlcheck->execute([$timestamp]);

Note that instead of concatenating strings, I am providing the $timestamp as a parameterized argument.

To check the result, you can't just check for string equality. Instead, use fetchColumn on the result object:

if ($timestem = $result->fetchColumn()) {
    echo "YES";
    // You can also use the value of `$timestem` here.
} else {
    echo "NO";
}

Note that this assumes there is only one row. For multiple rows, you need a loop. Note that only rows that match the condition are returned, so you will never see any NO output if you use a loop.

You can just as easily do the check in PHP (which will probably be a bit more straight-forward)

$sqlcheck = $dbh->prepare( "SELECT timestem FROM mytable" );
$sqlcheck->execute();

// You missed this step
$timestem = $sqlcheck->fetchColumn();

if ( time() - strtotime( $timestem ) > 10 )
    print 'yes';
else
    print 'no';

Some notes:

  1. In your code you didn't actually get the value out of the database. You used the result object in your conditional
  2. Your code implicitly assumes there is only ever one record in your table. This probably isn't true: you will need a where condition
  3. You have to be very certain that all of your timestamps are in the same time zone
  4. This will only work if you are using PDO, not mysqli. I can't tell the difference from your example, but a subtle difference is that PDO will allow you to use a prepare and execute with no bound parameters, but mysqli won't.