在WordPress上的月曆 – Theme後端資料庫的處理 (原月曆資料庫的作法)
本階段教學延續上一個工作myCalendar13移植至WordPress上,參考此篇教學:Part 9 使用AJAX方法將色彩名稱傳到後端並寫入資料庫。
將原本myCalendar13的sftp.json遠端目錄進行修改:
表格結構如下:
並新增一筆資料:(id永遠是1,cur_theme則是我們的色彩名稱,初始值為black或其他)
名稱只是參考,可以自己命名,但是記得程式裏的相關名稱要一致!
新增js/ajax.js,這支程式是前端與後端的資料橋樑:
最後這裏有一個問題,在WordPress裏,其實不需要再連接一次資料庫:
之後,我們會把資料庫的部份用WordPress的資料庫函式改寫。
{ "name": "My Server", "host": "u1085100.stu.fgchen.com", "protocol": "sftp", "port": 22, "username": "u1085100", "password": "這是密碼,不給你看…", "remotePath": "/home/u1085100/public_html/wp_dev/wp-content/themes/mycalendar14", "uploadOnSave": true }然後按F1->SFTP Local->Remote,將整個myCalendar13複製一份至遠端的mycalendar14目錄。 到WordPress控制台的外觀啟用mycalendar14。
資料庫與資料表格
使用後台phpMyAdmin (phpMy管理) 處理資料表格的建立,資料庫我們延用WordPress的,只要在這個資料庫上建立一個新的資料表格 wp_myCalendar_theme,資料庫的使用者與帳號可以透過WordPress裏的wp-config.php查。// ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define( 'DB_NAME', 'u1085100_wp_dev' ); /** MySQL database username */ define( 'DB_USER', 'u1085100_wp' ); /** MySQL database password */ define( 'DB_PASSWORD', '填上面帳號的密碼' );這邊我們知道,我們的WordPress的資料庫名稱是u1085100_wp_dev,因此,我們在這個資料庫上建立一個資料表格wp_myCalendar_theme



資料傳送AJAX函式與前端JavaScript程式
要從前端送或收資料,我們必須透過XMLHttpRequest 這個物件,此物件有一個很炫的名字叫ajax,第1個a點出這個物件最具代表性的特色:Asynchronous/非同步,非同步的意思是:前後端在交換資料時不需要彼此互相”等待”,一方需要資料時,告訴另一方,然後,轉頭做自己的事,另一方資料送到時,會被通知資料到了…。 這個月曆程式的資料更新邏輯,在個別資料(色彩與記事資料)變動時,資料由前端透過XMLHttpRequest送到後端,由後端的php程式處理。
function ajax(object){ var request = new XMLHttpRequest(); request.open("POST", "index.php"); request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.send(objectToString(object)); } function objectToString(object){ let str = ""; Object.keys(object).forEach(function(key){ str += key; str += `=${object[key]}&`; //``模板字符串 }); console.log(str); return str; }註:模版字符串(template literals,backtick 反引號,跟單引號不同)可以讓我們將變成或敘述插入在字串中。上面式子的等效傳統寫法 str += ‘=’ + object[key] + ‘&’; 我們在前端JavaScript程式中呼叫ajax(object)這個方法,我們將更新資料需求包裝在object物件裏,objectToString這個方法會將object這個物件的key與value值一個一個抓出來,組成key1=value1&key2&vaule2&…字串,再把這個字串送到後端處理。
PHP程式碼
<?php $connection = mysqli_connect("localhost", "u1085100_wp", "密碼…", "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)); } } if(isset($_POST['color'])){ //透過關聯陣列$_POST['color']取得傳送過來的color資料 db_updateTheme($_POST['color']); //呼叫db_updateTheme方法 } ?>ajax方法裏 request.open(“POST”, “index.php”); 這個敘述係利用POST方法來叫用index.php(接收資料的PHP碼所在的檔案),因此,在index.php裏加上取得資料的PHP程式碼,當透過ajax方法使用POST方法傳送color資料時,呼叫db_updateTheme方法更新theme表格中的color欄位 (id固定為1,因為整個月曆應用程式只有一筆色彩資料。) 此段程式流程:
- mysqli_connect方法連接資料庫,四個參數:localhost、使用者名稱(授權的資料庫使用者)、密碼、資料庫名稱
- if(!$connection),如果連結資料庫失敗(帳密錯誤、網路斷線…),使用die函式結束。
- if(isset($_POST[‘color’])),判斷是否透過http的POST方法傳進來color資料,是的話呼叫db_updateTheme($_POST[‘color’]);
- db_updateTheme函式將色彩代碼資料更新至資料表格theme中(指定id值為1的資料列),若執行sql查詢失敗的話,則使用die結束。
ajax({color: 'pink'});整段程式參考:
<script src="<?php echo get_stylesheet_directory_uri().'/js/updateDate.js'; ?>"></script> <script src="<?php echo get_stylesheet_directory_uri().'/js/changeTheme.js'; ?>"></script> <script src="<?php echo get_stylesheet_directory_uri().'/js/postIts.js'; ?>"></script> <script src="<?php echo get_stylesheet_directory_uri().'/js/ajax.js'; ?>"></script> <script> 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(); ajax({color: 'pink'}); updateDates(); fillInMonth(thisYear, thisMonth, thisDate); </script>更新網頁,然後檢視資料庫是否資料成功變更(cur_theme==>’pink’)。 沒問題之後,我們把測試的該行程式拿掉,在changeColor這個函式加入:
function changeColor(){ //將currentColor.name更新到資料庫 ajax({color:currentColor.name}); (以上略)
撰寫PHP函式讀取cur_theme欄位資料並回傳
當資料已經能夠寫入資料表後,我們就要在網頁載入時讀取資料表中的色彩名稱。在index.php加入一段php碼: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']; } }
這個函式會執行SQL敘述,查詢wp_myCalendar_theme表格中資料列,由於資料表只有一列,所以while迴圈只會執行一次,透過return的方式回傳cur_theme欄位所記錄的色彩名稱。
網頁載入讀取資料表裏的色彩名稱
<script> currentColor.name = <?php echo(json_encode(setTheme())); ?> ; //js_encode將回傳的資料包裝成字串,然後指定給currentColor.name 以下略 </script>
$connection = mysqli_connect("localhost", "u1085100_wp", "密碼…", "u1085100_wp_dev"); //連線資料庫 if(!$connection){ //如果連線失敗 die("There was an error connecting to the database."); //網頁宣告到此die,並在網頁輸出… }