我有类似的疑问
/* 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);
这将导致:
UPDATE `date` SET \'NULL\' WHERE `id` = $_POST[\'id\']
因此prepare()将单引号添加到NULL,查询将字段设置为NULL string not NULL value。我唯一的修复方法是在prepare()函数之外使用变量,如下所示:
/* 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);
最合适的回答,由SO网友:SequenceDigitale.com 整理而成
我找到的快速解决方案是str\\u替换空值。
/* 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);