Wordpress数据库insert()和update()-使用NULL值 [英] Wordpress database insert() and update() - using NULL values

查看:142
本文介绍了Wordpress数据库insert()和update()-使用NULL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Wordpress附带了处理CRUD操作的wpdb类.我感兴趣的该类的两个方法是insert()(CRUD中的C)和update()(CRUD中的U).

Wordpress ships with the wpdb class which handles CRUD operations. The two methods of this class that I'm interested in are the insert() (the C in CRUD) and update() (the U in CRUD).

当我想将NULL插入mysql数据库列时出现问题-wpdb类将PHP空变量转义为空字符串.如何告诉Wordpress使用实际的MySQL NULL代替MySQL字符串?

A problem arises when I want to insert a NULL into a mysql database column - the wpdb class escapes PHP null variables to empty strings. How can I tell Wordpress to use an actual MySQL NULL instead of a MySQL string?

推荐答案

如果要使其兼容,则必须显示列并提前确定是否允许使用NULL.如果允许,则如果该值为空($ v),则在查询中使用val = NULL.

If you want it to compatible you would have to SHOW COLUMN and determine ahead if NULL is allowed. If it was allowed then if the value was empty($v) use val = NULL in the query.

$foo = null;
$metakey = "Harriet's Adages";
$metavalue = "WordPress' database interface is like Sunday Morning: Easy.";

if ($foo == null) {
$wpdb->query( $wpdb->prepare( "
    INSERT INTO $wpdb->postmeta
    ( post_id, meta_key, meta_value, field_with_null )
    VALUES ( %d, %s, %s, NULL )", 
        10, $metakey, $metavalue ) );
} else {
$wpdb->query( $wpdb->prepare( "
    INSERT INTO $wpdb->postmeta
    ( post_id, meta_key, meta_value, field_with_null )
    VALUES ( %d, %s, %s, %s)", 
        10, $metakey, $metavalue, $foo ) );
}

这篇关于Wordpress数据库insert()和update()-使用NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆