Marian Rick Marian Rick - 1 month ago 7
MySQL Question

How to check if MYSQL field is null and replace with current timestamp?

I am using a Wordpress and got a database with different

pid
s (personal ids) and a field
activatedValue
which is already set to
NULL
or the
current_time()
.

I got the
pid
and need to find its
activatedValue
-value. Than if the field is
NULL
, I want to replace it with
current_time()
. I thought about something like this:

$pid = '52'; // example for a personal id
$activatedValue = $wpdb->get_var( "SELECT activatedValue FROM $table_name WHERE pid = '$pid'" );

if( is_null($activatedValue) ) {
// replace activatedValue in database with current time
}


How can I do this?




There are several problems for me in achieving this. I have tried this:

$pid = '52';

if ( ! empty ( $pid ) ) {

global $wpdb;
$table_name = $wpdb->prefix . "prelaunchr";
$activatedValue = $wpdb->get_var( "SELECT activated FROM $table_name WHERE pid = '$pid'" );

if ( is_null($activatedValue) ) {
$currentTime = current_time();
$wpdb->query("UPDATE $table_name SET activated = NOW() WHERE pid = '$pid'");
}
}

Answer

If you want to update the value in the database record, you will need to run an UPDATE statement, using wpdb::query().

if( is_null($example_field) ) {
    $wpdb->query("UPDATE $table_name SET example_field = NOW() WHERE pid = '$pid'");
}