Part 10 實現記事資料的CRUD(Create, Read, Update, Delete)
這個階段,我們要將前端的記事資料新增(Create)到資料庫、更新((Update)資料庫中的現有記事資料、刪除(Delete)在資料庫中的記事資料,最後,我們要從資料庫中把所有的記事資料讀取出來(Read),並且更新前端中的記事資料,完成整個記事資料的CRUD。
首先我們建立記事資料所需要使用到的資料表格notes,notes資料表格有4個欄位:
- id, int(12), 主鍵,auto_increment(不用給值自動依照前筆資料的值加1)
- note_id, varchar(12)
- note_color, int(10)
- note_text, text
注意:當寫入中文字到資料表格時,會有亂碼的疑慮,此時需要確認二件事:
- 資料表格的編碼必須是utf8mb4_unicode… 或 utf8mb4_開頭?????,這個大家可以測試一下。
- 需要在php程式中加入一行: mysqli_query($connection, “SET NAMES ‘utf8′”);
<?php
$connection = mysqli_connect("localhost", "wda2216_wda2216", "h1mwm5p9bywt", "wda2216_calendar"); //連線資料庫
if(!$connection){ //如果連線失敗
die("There was an error connecting to the database."); //網頁宣告到此die,並在網頁輸出…
}
mysqli_query($connection, "SET NAMES 'utf8'"); //解決中文字亂碼問題
(以下略)
Create
首先在index.php中的php程式區塊加入:function db_insertNote($uid, $color, $text){ //新增記事資料函式
global $connection;
$text = mysqli_real_escape_string($connection, $text);
$query = "INSERT INTO notes(note_id, note_color, note_text) VALUES('$uid', '$color', '$text')";
$result = mysqli_query($connection, $query);
if(!$result){
die("Something went wrong...");
}
}
if(isset($_POST['new_note_uid'])){ //前端傳來新增記事資料
db_insertNote($_POST['new_note_uid'], $_POST['new_note_color'], $_POST['new_note_text']);
}
上面這段程式先判斷是否從前端有傳來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();
}
Update
接著,處理記事資料的更新,同樣的把下面的PHP插入到index.php中的PHP段:function db_updateNote($uid, $text){//更新記事資料函式
global $connection;
$text = mysqli_real_escape_string($connection, $text);
$query = "UPDATE notes SET note_text = '$text' WHERE note_id = '$uid' LIMIT 1";
$result = mysqli_query($connection, $query);
if(!$result){
die("Something went wrong....");
}
}
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呼叫
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(); //因為記事資料變了,呼叫fillInMonth重新產出月曆表格
closeMakeNote();
}
Delete
PHP段:function db_deleteNote($uid){ //刪除記事資料函式
global $connection;
$query = "DELETE FROM notes WHERE note_id = '$uid'";
$result = mysqli_query($connection, $query);
if(!$result){
die("Something went wrong…");
}
}
if(isset($_POST['delete_note_uid'])){ //刪除記事資料
db_deleteNote($_POST['delete_note_uid']);
}
postIt.js中的deleteNote函式,一開始就加入 ajax呼叫:
function deleteNote(){//刪除點擊日期的記事資料
if(!newCurrentPostIt) { //如果點擊的日期是有記事資料話
//加入刪除記事資料的ajax呼叫
ajax({delete_note_uid: postIts[currentPostItIndex].id});
//使用splice刪除掉點擊日期的記事資料
postIts.splice(currentPostItIndex, 1);
console.log(postIts);
document.getElementById("edit-post-it").value = "";
//因為記事資料變動了
//呼叫fiilInMonth方法重新繪製一次月曆表格
fillInMonth();
}
closeMakeNote();
}
Read
在index.php程式的PHP段加入:<?php
function getNoteData(){
global $connection;
$query = "SELECT * FROM notes";
$result = mysqli_query($connection, $query);
if(!$result){
die("Something went wrong");
}
$id = 0;
$color = 1;
$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(); ?>index.php後段的程式碼如下:
<!-- 底下是JavaScript程式碼 -->
<script src="jsupdateData.js"></script>
<script src="jstheme.js"></script>
<script src="jspostIt.js"></script>
<script src="jsajax.js"></script>
//透過PHP的getNoteData函式,查詢資料庫所有的記事資料,以JSON的方式呈現。
<?php getNoteData(); ?>
<script>
//測試送出一組顏色到後端,寫入到資料庫
// ajax( { color : 'orange' } );
//呼叫PHP的setTheme()方法,抓取資料庫中的theme名稱
//抓取到的theme指定給currentColor.name
currentColor.name = <?php echo(json_encode(setTheme())); ?> ;
updateData();
var today = new Date();
var thisYear = today.getFullYear();
var thisMonth = today.getMonth();
fillInMonth();
</script>
