問題描述
當我嘗試這樣的東西
$status = NULL;
$wpdb->update(
'table',
array(
'status' => $status,
),
array( 'id' => 1 )
);
在’status’ 列中,現在我有一個空字串'',它根本不會將其設定為 NULL 。
當然列可以為 NULL 。我也測試了 $ wpdb-> 查詢和 $ wpdb-> 準備,結果是一樣的。我做錯了嗎?
最佳解決方案
更新:
自 WordPress 4.4 。現在由 insert,update,replace 和 delete wpdb 的 wpdb 方法得到支援,而 #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 inwpdb::$field_types.
您可以指定格式,但允許的說明符是:
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.
您可以 read through the source 並制定出該過程。
如果您劫持 wpdb->prepare 方法 (在定期清除擦除的開發者伺服器上):) 在返回之前轉儲 SQL,您將看到替換髮生在 wpdb->prepare 之前:
string(48) "UPDATE `table` SET `status` = %s WHERE `id` = %s"
儘管如 @birgire 所建議的那樣,對於 prepare 來說,這可能是一個限制。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。