Domanda

I have similars queries

/* Query */
global $wpdb;
$tablename = $wpdb->prefix . 'data';
$sql = $wpdb->prepare(
    "
    UPDATE $tablename
    SET
        `date` = %s,
    WHERE
        id= %d
    ",
    $_POST['date'] == '' ? "NULL": $_POST['date'],
    $_POST['id']
);
$wpdb->query($sql);

This will results in:

UPDATE `date` SET 'NULL' WHERE `id` = $_POST['id'] 

so prepare() is adding single quotes to NULL and the query sets the field to NULL string not NULL value. The only fix for me is to take the variable outside of the prepare() function like this:

/* Query */
global $wpdb;
$tablename = $wpdb->prefix . 'data';

/* Here I declare the variabile outside of the prepare() */
$date = $output['date'] == '' ? "NULL" : $_POST['date'];
$sql = $wpdb->prepare(
    "
    UPDATE $tablename
    SET
        `date` = $date,
    WHERE
        id = %d
    ",
    $_POST['id']
);
$wpdb->query($sql);
È stato utile?

Soluzione

the quick solution I found is to str_replace empty value.

/* Query */
global $wpdb;
$tablename = $wpdb->prefix . 'data';
$sql = $wpdb->prepare(
    "
    UPDATE $tablename
    SET
        `date` = %s,
    WHERE
        id= %d
    ",
    $_POST['date'],
    $_POST['id']
);
// SQL = UPDATE prefix_data SET `date` = '' WHERE id = 1


$sql = str_replace("''",'NULL', $sql);
// SQL = UPDATE prefix_data SET `date` = NULL WHERE id = 1

$wpdb->query($sql);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange
scroll top