問題描述

當我嘗試這樣的東西

    $status = NULL;

    $wpdb->update(
            'table',
            array(
                'status' => $status,
            ),
            array( 'id' => 1 )
    );

在’status’ 列中,現在我有一個空字符串'',它根本不會將其設置為 NULL 。

當然列可以為 NULL 。我也測試了 $ wpdb-> 查詢和 $ wpdb-> 準備,結果是一樣的。我做錯了嗎?

最佳解決方案

更新:

自 WordPress 4.4 。現在由 insertupdatereplacedelete wpdbwpdb 方法得到支持,而 #15158 的票已經被封閉。

感謝 @dmsnell 的 commenting 關於該更新。

另一方面,wpdb::prepare()中的 null 支持目前在門票 #12819 中作為 wontfix 關閉。

以前的答案:

不支持 NULL

看起來你必須編寫自己的自定義 SQL 來更新 NULL 的值。

目前,$wpdb->prepare()不支持 NULL,它通過 vsprintf 格式化函數獲取輸入。

查看這些打開的 Trac 門票:

這些門票大約 4 歲,所以我不會忍受,直到得到核心的支持;-)

你應該看看源為 @s_ha_dum 建議。

可能的解決方法:

如果你是冒險的,可以嘗試以下 query 過濾器:

    // Add a filter to replace the 'NULL' string with NULL
    add_filter( 'query', 'wpse_143405_query' );

    global $wpdb;
    $wpdb->update(
        'table',
        array(
            'status' => 'NULL',
        ),
        array( 'id' => 1 )
    );

    // Remove the filter again:
    remove_filter( 'query', 'wpse_143405_query' );

哪裏

/**
 * Replace the 'NULL' string with NULL
 *
 * @param  string $query
 * @return string $query
 */

function wpse_143405_query( $query )
{
    return str_ireplace( "'NULL'", "NULL", $query );
}

您可能希望使用比'NULL'更為獨特的字符串來替換,也可能是'###NULL###'

次佳解決方案

wpdb->update 默認為所有數據類型的字符串。

format
(array|string) (optional) An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.

http://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows

您可以指定格式,但允許的説明符是:

Possible format values: %s as string; %d as integer (whole number) and %f as float. (See below for more information.) If omitted, all values in $where will be treated as strings.

http://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows

您可以 read through the source 並制定出該過程。

如果您劫持 wpdb->prepare 方法 (在定期清除擦除的開發者服務器上):) 在返回之前轉儲 SQL,您將看到替換髮生在 wpdb->prepare 之前:

string(48) "UPDATE `table` SET `status` = %s WHERE `id` = %s"

儘管如 @birgire 所建議的那樣,對於 prepare 來説,這可能是一個限制。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。