使用WordPress資料庫函式處理月曆資料 (整合現有WordPress資料庫)
PHP段的原始碼:
<?php
//$wpdb->prefix是WordPress設定時所指定的資料表格前綴
function db_updateTheme($newTheme){
global $wpdb;
$table = $wpdb->prefix."myCalendar_theme";
$wpdb->update(
$table,
array("cur_theme" => $newTheme),
array("id" => 1),
array("%s"),
array("%d")
);
}
function setTheme(){
global $wpdb;
$table = $wpdb->prefix.'myCalendar_theme';
$query = $wpdb->prepare("SELECT cur_theme FROM $table where id='1'");
$theme = $wpdb->get_var($query);
return $theme;
}
if(isset($_POST['color'])){ //透過關聯陣列$_POST['color']取得傳送過來的color資料
db_updateTheme($_POST['color']); //呼叫db_updateTheme方法
}
?>
底下程式碼是未使用WordPress的資料庫函式:
<?php
$connection = mysqli_connect("localhost", "u1085100_wp", "@p2MgKw6pj)]", "u1085100_wp_dev"); //連線資料庫
if(!$connection){ //如果連線失敗
die("There was an error connecting to the database."); //網頁宣告到此die,並在網頁輸出…
}
function db_updateTheme($newTheme){
global $connection;
$query = "UPDATE wp_myCalendar_theme SET cur_theme = '$newTheme' WHERE id = 1"; //更新theme資料表格中,id欄位值為1的資料列中的cur_theme欄位值為$newTheme
$result = mysqli_query($connection, $query); //送出SQL查詢
if(!$result){ //查詢失敗的話…
die("Query failed: " . mysqli_error($connection));
}
}
function setTheme(){
global $connection;
$query = "SELECT * FROM wp_myCalendar_theme";
$result = mysqli_query($connection, $query);
if(!$result){
die("Something went wrong...`");
}
while($row = mysqli_fetch_assoc($result)){
return $row['cur_theme'];
}
}
if(isset($_POST['color'])){ //透過關聯陣列$_POST['color']取得傳送過來的color資料
db_updateTheme($_POST['color']); //呼叫db_updateTheme方法
}
?>
比較二段原始碼,使用WordPress資料庫就不必再取得資料庫的存取連結,直接使用$wpdb這個全域變數物件。
詳細的$wpdb的說明請參考另二篇我寫在日誌的文章:
為了日後能夠系統寫得好,SQL的基礎很重要,請參考這篇文章,好好練習SQL,也同時了解SQL能做些什麼事情:資料庫-SQL & MySQL 。
