Home > other >  Count records after specific date in SQL and get result
Count records after specific date in SQL and get result

Time:07-19

I use WordPress and I try to count records from database WHERE datetime > $user_last_seen

So I use query

$message_count = $wpdb->get_results( "SELECT COUNT(datetime) FROM user_messages WHERE datetime > " . $user_last_seen );

And I get result

Array ( [0] => stdClass Object ( [COUNT(datetime)] => 3 ) )

I want to get count (3) so I try

$message_count = $message_count[0]->COUNT(datetime);

But I get error

CodePudding user response:

You can access the objects property by enclosing in curly braces and quotes. You need to do it this way, because of the special chars like parenthesis which are not allowed in variable names.

$message_count = $message_count[0]->{'COUNT(datetime)'};

You could also alter the query to give the field a different name

$message_count = $wpdb->get_results( "SELECT COUNT(datetime) AS counted FROM user_messages WHERE datetime > " . $user_last_seen );
$message_count = $message_count[0]->counted;
  • Related