admin管理员组文章数量:1300261
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);
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);
Share
Improve this question
asked Nov 20, 2020 at 8:23
silvered.dragonsilvered.dragon
1134 bronze badges
1 Answer
Reset to default 0the 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);
本文标签: databaseInsert NULL value using prepare()
版权声明:本文标题:database - Insert NULL value using prepare() 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741628939a2389244.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论