使用WordPress資料庫函式處理記事資料庫 (整合現有WordPress資料庫)
建立記事資料庫
建立記事資料所需要使用到的資料表格notes,notes資料表格有4個欄位:- id, int(12), 主鍵,auto_increment(不用給值自動依照前筆資料的值加1)
- note_id, varchar(12)
- note_color, int(10)
- note_text, text

記事資料的CRUD(Create, Read, Update, Delete)
記事資料的新增 – Create
首先在index.php中的php程式區塊加入db_insertNote函式,這個函式的目的是使用SQL的Insert into句子將一筆資料加入一個資料表格中。 Insert into語法:INSERT INTO "表格名" ("欄位1", "欄位2", ...) VALUES ("值1", "值2", ...);
後端PHP程式片段 (所謂後端程式是由伺服端所執行的程式碼,在這邊我們是使用PHP)
function db_insertNote($uid, $color, $text){ //新增記事資料函式 global $wpdb; //宣告WordPress的全域資料庫物件 $text = $wpdb->_real_escape($text); $wpdb->insert($wpdb->prefix."mycalendar_notes", array( "note_id" => $uid, "note_color" => $color, "note_text" => $text ),array( "%s", "%s", "%s" )); // $query = "INSERT INTO notes(note_id, note_color, note_text) VALUES('$uid', '$color', '$text')"; // $result = mysqli_query($connection, $query); } if(isset($_POST['new_note_uid'])){ //前端傳來新增記事資料 db_insertNote($_POST['new_note_uid'], $_POST['new_note_color'], $_POST['new_note_text']); }
前端JavaScript程式片段
上面這段程式先判斷是否從前端有傳來new_note_uid記事資料,若有的話,就將傳來的記事資料3個欄位值(note_uid, note_color, note_text)作為參數呼叫db_insertNote函式,此函式執行SQL的Insert into新增查詢,將資料寫入到資料庫。 接著,我們要在前端程式中處理新增記事資料的程式(postIt.js裏的submitPostIt函式)區塊中加入程式碼:ajax({new_note_uid: postIt.id, new_note_color: postIt.note_num, new_note_text: postIt.note});整個submitPostIt函式列表如下:
function submitPostIt(){ //按了PostIt按鍵後,所要執行的方法 const value = document.getElementById("edit-post-it").value; document.getElementById("edit-post-it").value = ""; let num = getRandom(1, 6); //取得1~5的亂數,用來標示便利貼顏色的檔案代號 let postIt = { id: currentPostItID, note_num: num, note: value } if(newCurrentPostIt){ //如果是新記事的話 postIts.push(postIt); //將新記事postIt物件推入postIts記事資料陣列 //加入新增記事資料的ajax呼叫 ajax({new_note_uid: postIt.id, new_note_color: postIt.note_num, new_note_text: postIt.note}); } else {//目前有記事資料的話 //更新現有記事物件的記事資料 postIts[currentPostItIndex].note = postIt.note; } console.log(postIts) fillInMonth(); //因為記事資料變了,呼叫fillInMonth重新產出月曆表格 closeMakeNote(); }測試的方式是從月曆那邊新增記事,然後到資料庫那邊觀察前端新增的資料是否有成功加入notes資料表中。
Update
在月曆中,記事資料是可以修改的,修改在SQL的中是透過update語句完成,update的語法:UPDATE "表格名" SET "欄位1" = [新值] WHERE "條件";
後端處理程式
同樣的把下面的PHP插入到index.php中的PHP段(後端):function db_updateNote($uid, $text){//更新記事資料函式 global $wpdb; //宣告WordPress的全域資料庫物件 $text = $wpdb->_real_escape($text); $wpdb->update( $wpdb->prefix."mycalendar_notes", array( "note_text" => $text ), array("note_id" => $uid), array("%s"), array("%s") ); // $query = "UPDATE notes SET note_text = '$text' WHERE note_id = '$uid' LIMIT 1"; } if(isset($_POST['update_note_uid'])){ //若前端有傳來更新記事資料 db_updateNote($_POST['update_note_uid'], $_POST['update_note_text']); }
前端處理程式
將下面ajax傳送更新資料的程式加入到submitPostIt函式裏的更新記事資料段落://加入更新記事資料的ajax呼叫 ajax({update_note_uid: postIts[currentPostItIndex].id, update_note_text: postIt.note});最新的submitPostIt函式列表如下:
function submitPostIt(){ //按了PostIt按鍵後,所要執行的方法 const value = document.getElementById("edit-post-it").value; document.getElementById("edit-post-it").value = ""; let num = getRandom(1, 6); //取得1~5的亂數,用來標示便利貼顏色的檔案代號 let postIt = { id: currentPostItID, note_num: num, note: value } if(newCurrentPostIt){ //如果是新記事的話 postIts.push(postIt); //將新記事postIT物件推入postIts陣列 ajax({new_note_uid: postIt.id, new_note_color: postIt.note_num, new_note_text: postIt.note}); } else { postIts[currentPostItIndex].note = postIt.note; //更新現有記事物件的記事資料 //加入更新記事資料的ajax呼叫 ajax({ update_note_uid: postIts[currentPostItIndex].id, update_note_text: postIt.note }); } // console.log(postIts) fillInMonth(thisYear, thisMonth, thisDate); closeMakeNote(); }Delete 接著我們使用SQL的Delete語句將Notes記事資料表中的一筆記事資料進行刪除,Delete的語法如下: DELETE FROM “表格名” WHERE “條件”;
後端處理程式
function db_deleteNote($uid){ //刪除記事資料函式 global $wpdb; //宣告WordPress的全域資料庫物件 $wpdb->delete( $wpdb->prefix."mycalendar_notes", array("note_id" => $uid), array("%s") ); // $query = "DELETE FROM notes WHERE note_id = '$uid'"; } if(isset($_POST['delete_note_uid'])){ //刪除記事資料 db_deleteNote($_POST['delete_note_uid']); }這部份的後端PHP程式接收來自己前端的POST資料發送,前端送出delete_note_uid=uid的資料格式給後端,後端PHP程式從$_POST[‘delete_note_uid’]判斷是否有資料,有資料的話,呼叫db_deleteNote這支PHP函式,對記事資料uid進行刪除。
前端處理程式
postIt.js中的deleteNote函式,一開始就加入 ajax呼叫:function deleteNote(){ document.getElementById("edit-post-it").value = ""; let indexToDel; //指向將刪除的記事資料物件 if(!newCurrentPostIt){ //加入刪除記事資料的ajax呼叫 ajax({delete_note_uid: postIts[currentPostItIndex].id}); indexToDel =currentPostItIndex; } if(indexToDel != undefined){ postIts.splice(indexToDel, 1); } fillInMonth(thisYear, thisMonth, thisDate); closeMakeNote(); }ajax({delete_note_uid: postIts[currentPostItIndex].id}); 此行將目前記事資料的id送到後端,由後端PHP程式以SQL的方式將該資料從資料表格中刪除掉。 上面是記事資料新增、更新與維護的三個動作,最後,我們要在程式一開始的時候,把所有的記事資料進行查詢(SQL select),一筆一筆的資料讀出來後,echo成JSON物件敘述,再將這些資料JSON物件一一加入PostIts記事資料陣列中。
Read
後端處理程式
在index.php程式的PHP段加入:<?php function getNoteData(){ global $wpdb; //宣告WordPress的全域資料庫物件 // $query = "SELECT * FROM notes"; $data = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."mycalendar_notes"); $id = 0; $color = 1; $text = ""; foreach ($data as $row) { $id = $row->note_id; $color = $row->note_color; $text = $row->note_text; // while($row = mysqli_fetch_assoc($result)){ // $id = $row['note_id']; // $color = $row['note_color']; // $text = $row['note_text']; //以上為php碼 ?> <script type="text/javascript"> postIt = { id: <?php echo json_encode($id); ?>, note_num: <?php echo json_encode($color); ?>, note: <?php echo json_encode($text); ?> } postIts.push(postIt); </script> <?php //再接著php碼,這種寫法在混合式的php、html、JavaScript很常見的寫法,要習慣。 } } ?>
前端處理程式
之後再到index.php中的後段(在<script>前)加入:<?php getNoteData(); ?> <script> currentColor.name = <?php echo json_encode(setTheme()); ?> ; var stylesheet_directory = "<?php echo get_stylesheet_directory_uri();?>";//取得主題所在的路徑,此stylesheet_directory變數要在後面的JS程式中被使用 <?php global $current_user; wp_get_current_user(); if ( is_user_logged_in() ) { //如果WordPress使用者有登入的話 echo "var currentUserName = ".'"'.$current_user->display_name.'";'; } ?> if (typeof currentUserName !== 'undefined') {//若currentUserName不是未定義的話… document.getElementById("app-name-landscape").innerHTML = currentUserName; document.getElementById("app-name-portrait").innerHTML = currentUserName; } let today = new Date(); //新增一個Date物件,命名為today let thisYear = today.getFullYear(); let thisMonth = today.getMonth(); let thisDate = today.getDate(); updateDates(); fillInMonth(thisYear, thisMonth, thisDate); </script>後續幾週的程式碼下載