[WordPress] 使用 $wpdb 資料庫方法快速批次新增資料

本篇文章更新時間:2021/06/08
如有資訊過時或語誤之處,歡迎使用 Contact 功能通知。
一介資男的 LINE 社群開站囉!歡迎入群聊聊~
如果本站內容對你有幫助,歡迎使用 BFX Pay 加密貨幣新台幣 贊助支持。


寫在前面,這篇我應該會列為每次建立針對 WordPress 資料庫讀寫專案時,必用的方法!

$wpdb 這個資料庫存取方法,官方文件有寫使用手冊

不過就是簡單的「增刪查改」 CRUD 四大方法介紹。如果再細看「新增」的方法 insert( $table, $data, $format );

會發現除了基本指定 資料表資料 外,還要指定 資料的型態。 這實在有夠麻煩,尤其是有些資料表有 20~30 個欄位的話,那個型態就會寫得很頭痛。想到就覺得不爽!

不過我相信有這困擾的人不只有我,果然 Google 一下發現有網友開源一個很棒的方法:

function wpdb_bulk_insert($table, $rows) {
    global $wpdb;

    // Extract column list from first row of data
    $columns = array_keys($rows[0]);
    asort($columns);
    $columnList = '`' . implode('`, `', $columns) . '`';

    // Start building SQL, initialise data and placeholder arrays
    $sql          = "INSERT INTO `$table` ($columnList) VALUES\n";
    $placeholders = array();
    $data         = array();

    // Build placeholders for each row, and add values to data array
    foreach ($rows as $row) {
        ksort($row);
        $rowPlaceholders = array();

        foreach ($row as $key => $value) {
            $data[]            = $value;
            $rowPlaceholders[] = is_numeric($value) ? '%d' : '%s';
        }

        $placeholders[] = '(' . implode(', ', $rowPlaceholders) . ')';
    }

    // Stitch all rows together
    $sql .= implode(",\n", $placeholders);
    // print_r($sql);
    // Run the query.  Returns number of affected rows.
    return $wpdb->query($wpdb->prepare($sql, $data));
}

這個方法包裝了 $wpdb,解決了要輸入 資料型態 的困擾(儘管只是判斷是數字還是字串,但要自己一個一個列真的痛苦)。

使用方式除了帶入第一個 資料表 參數外,第二個參數是要帶入「陣列」的資料列。意味著這方法也幫你做到了批次新增,一舉兩得的好方法啊啊啊啊啊~~~


Share:

作者: Chun

資訊愛好人士。主張「人人都該為了偷懶而進步」。期許自己成為斜槓到變進度條 100% 的年輕人。[///////////____36%_________]

參與討論

  1. none
  2. Chun

2 則留言

    1. yes, but WordPress will auto convert numeric string to number(INT) format. It will cause database error. make sure your input data type is very important.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


文章
Filter
Apply Filters
Mastodon