php+mysql簡單的新增和刪除小案例
阿新 • • 發佈:2018-11-10
1.分析
index.php是呈現列表,通過點選列表頁上的新增和刪除按鈕,對列表頁上面的進行操作
index.php
TODO:要將資料庫裡面的內容呈現到頁面中
(1)連線資料庫
(2)查詢資料
(3)混編
<?php //連線資料庫 $connection=mysqli_connect('localhost','root','123','test'); if(!$connection){ exit('<h1>資料庫連線失敗</h2>'); } //建立查詢 $query = mysqli_query($connection,'select * from users;'); if(!$query){ exit('資料庫查詢失敗'); } //轉為陣列 /*while($item = mysqli_fetch_assoc($query)){ var_dump($item); }*/ ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>XXX管理系統</title> <link rel="stylesheet" href="assets/css/bootstrap.css"> <link rel="stylesheet" href="assets/css/style.css"> </head> <body> <nav class="navbar navbar-expand navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">XXX管理系統</a> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="index.html">使用者管理</a> </li> <li class="nav-item"> <a class="nav-link" href="#">商品管理</a> </li> </ul> </nav> <main class="container"> <h1 class="heading">使用者管理 <a class="btn btn-link btn-sm" href="add.php">新增</a></h1> <table class="table table-hover"> <thead> <tr> <th><input type="checkbox" name="check[]"></th> <th>#</th> <th>頭像</th> <th>姓名</th> <th>性別</th> <th>年齡</th> <th class="text-center" width="140">操作</th> </tr> </thead> <tbody> <?php while($item = mysqli_fetch_assoc($query)): ?> <tr> <th><input type="checkbox" name="check[]"></th> <th scope="row"><?php echo $item['id']; ?></th> <td><img src="<?php echo $item['src']; ?>" class="rounded" alt="<?php echo $item['name']; ?>"></td> <td><?php echo $item['name']; ?></td> <td><?php echo $item['gender'] == 0 ? '♀' : '♂'; ?></td> <td><?php echo $item['birthday']; ?></td> <td class="text-center"> <a class="btn btn-info btn-sm" href="edit.php?id=<?php echo $item['id'];?>">編輯</a> <a class="btn btn-danger btn-sm" href="delete.php?id=<?php echo $item['id'];?>">刪除</a> </td> </tr> <?php endwhile ?> </tbody> </table> <ul class="pagination justify-content-center"> <li class="page-item"><a class="page-link" href="#">«</a></li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"><a class="page-link" href="#">»</a></li> </ul> </main> </body> </html>
add.php
DOTO:在資料庫裡面新增資料
(1)表單驗證 (2)持久化( 3)響應
需要注意的幾個問題:
(1)在單選中,value=-1預設是沒有選中
<?php function add(){ //目標:表單驗證,持久化,響應 //表單驗證 //驗證姓名 if(empty($_POST['name'])){ $GLOBALS['error_message'] = '請輸入姓名'; return ; } if(!(isset($_POST['gender'])&&$_POST['gender']!=='-1')){ $GLOBALS['error_message'] = '請選擇性別'; return; } if(empty($_POST['birthday'])){ $GLOBALS['error_message'] = '請選擇生日'; return; } $name=$_POST['name']; $gender=$_POST['gender']; $birthday=$_POST['birthday']; //頭像驗證 if (empty($_FILES['src'])) { $GLOBALS['error_message'] = '請上傳頭像'; return; } $ext = pathinfo($_FILES['src']['name'], PATHINFO_EXTENSION); // => jpg $target = '../uploads/avatar-' . uniqid() . '.' . $ext; if (!move_uploaded_file($_FILES['src']['tmp_name'], $target)) { $GLOBALS['error_message'] = '上傳頭像失敗'; return; } $src = substr($target, 2); //持久化,將資料儲存到資料庫中 //連線資料庫 $connection=mysqli_connect('localhost','root','123','test'); if(!$connection){ $GLOBALS['error_message'] = '資料庫連線失敗'; } $query = mysqli_query($connection, "insert into users values (null, '{$name}', {$gender}, '{$birthday}', '{$src}');"); //建立查詢 if(!$query){ $GLOBALS['error_message'] = '資料庫插入失敗'; } //響應 header('Location: index.php'); } if($_SERVER['REQUEST_METHOD']=='POST'){ add(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>XXX管理系統</title> <link rel="stylesheet" href="assets/css/bootstrap.css"> <link rel="stylesheet" href="assets/css/style.css"> </head> <body> <nav class="navbar navbar-expand navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">XXX管理系統</a> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="index.html">使用者管理</a> </li> <li class="nav-item"> <a class="nav-link" href="#">商品管理</a> </li> </ul> </nav> <main class="container"> <h1 class="heading">新增使用者</h1> <?php if (isset($error_message)): ?> <div class="alert alert-warning"> <?php echo $error_message; ?> </div> <?php endif ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" autocomplete="off"> <div class="form-group"> <label for="avatar">頭像</label> <input type="file" class="form-control" id="avatar" name="src"> </div> <div class="form-group"> <label for="name">姓名</label> <input type="text" class="form-control" id="name" name="name"> </div> <div class="form-group"> <label for="gender">性別</label> <select class="form-control" id="gender" name="gender"> <option value="-1">請選擇性別</option> <option value="1">男</option> <option value="0">女</option> </select> </div> <div class="form-group"> <label for="birthday">生日</label> <input type="date" class="form-control" id="birthday" name="birthday"> </div> <button class="btn btn-primary">儲存</button> </form> </main> </body> </html>
edit.php
注意的問題:
(1)這裡需要加上一個空格,屬性和屬性之間必須要有空格,
(2)如果gender=" " 這是不選中的情況,但是null==0,返回的是TRUE,
(3)<input type="text hidden>可以隱藏該表單
(4)非常重要的問題
在html中,函式裡面不能使用函式外面的變數,如果要使用應該都宣告為全域性變數
<?php // 接收要修改的資料 ID if (empty($_GET['id'])) { exit('<h1>必須傳入指定引數</h1>'); } $id = $_GET['id']; // 1. 建立連線 $conn = mysqli_connect('localhost', 'root', '123', 'test'); if (!$conn) { exit('<h1>連線資料庫失敗</h1>'); } // 2. 開始查詢 // 因為 ID 是唯一的 那麼找到第一個滿足條件的就不用再繼續了 limit 1 $query = mysqli_query($conn, "select * from users where id = {$id} limit 1;"); if (!$query) { exit('<h1>查詢資料失敗</h1>'); } // 已經查詢到的當前資料 $user = mysqli_fetch_assoc($query); if (!$user) { exit('<h1>找不到你要編輯的資料</h1>'); } function edit () { global $user; global $conn,$query; // 驗證非空 if (empty($_POST['name'])) { $GLOBALS['error_message'] = '請輸入姓名'; return; } if (!(isset($_POST['gender']) && $_POST['gender'] !== '-1')) { $GLOBALS['error_message'] = '請選擇性別'; return; } if (empty($_POST['birthday'])) { $GLOBALS['error_message'] = '請輸入日期'; return; } // 取值 $user['name'] = $_POST['name']; $user['gender'] = $_POST['gender']; $user['birthday'] = $_POST['birthday']; // 有上傳就修改 if (isset($_FILES['src']) && $_FILES['src']['error'] === UPLOAD_ERR_OK) { // 使用者上傳了新頭像 -> 使用者希望修改頭像 $ext = pathinfo($_FILES['src']['name'], PATHINFO_EXTENSION); $target = '../uploads/avatar-' . uniqid() . '.' . $ext; if (!move_uploaded_file($_FILES['src']['tmp_name'], $target)) { $GLOBALS['error_message'] = '上傳頭像失敗'; return; } $user['src'] = substr($target, 2); } // $user => 修改過後的資訊 // TODO: 將資料更新回資料庫 $newdata=mysqli_query($conn,"update users set name='{$user['name']}', gender={$user['gender']},birthday='{$user['birthday']}',src='{$user['src']}' where id={$user['id']} limit 1;"); if(!$newdata){ $GLOBALS['error-message'] = '更新資料失敗'; } header('Location: index.php'); } if ($_SERVER['REQUEST_METHOD'] === 'POST') { edit(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>XXX管理系統</title> <link rel="stylesheet" href="assets/css/bootstrap.css"> <link rel="stylesheet" href="assets/css/style.css"> </head> <body> <nav class="navbar navbar-expand navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">XXX管理系統</a> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="index.html">使用者管理</a> </li> <li class="nav-item"> <a class="nav-link" href="#">商品管理</a> </li> </ul> </nav> <main class="container"> <h1 class="heading">編輯“<?php echo $user['name']; ?>”</h1> <form action="<?php echo $_SERVER['PHP_SELF']; ?>?id=<?php echo $user['id']; ?>" method="post" enctype="multipart/form-data"> <!-- <input type="hidden" id="id" value="<?php echo $user['id']; ?>"> --> <img src="<?php echo $user['avatar']; ?>" alt=""> <div class="form-group"> <label for="avatar">頭像</label> <!-- 檔案域不能設定預設值 --> <input type="file" class="form-control" id="avatar" name="avatar"> </div> <div class="form-group"> <label for="name">姓名</label> <input type="text" class="form-control" id="name" name="name" value="<?php echo $user['name']; ?>"> </div> <div class="form-group"> <label for="gender">性別</label> <select class="form-control" id="gender" name="gender"> <option value="-1">請選擇性別</option> <option value="1"<?php echo $user['gender'] === '1' ? ' selected': ''; ?>>男</option> <option value="0"<?php echo $user['gender'] === '0' ? ' selected': ''; ?>>女</option> </select> </div> <div class="form-group"> <label for="birthday">生日</label> <input type="date" class="form-control" id="birthday" name="birthday" value="<?php echo $user['birthday']; ?>"> </div> <button class="btn btn-primary">儲存</button> </form> </main> </body> </html>
delete.php
<?php
$id = $_GET['id'];
//建立資料庫連線
$conncetion=mysqli_connect('localhost','root','123','test');
if(!$conncetion){
exit('<h1>資料庫連線失敗</h1>');
}
//查詢
$query=mysqli_query($conncetion,'delete from users where id='.$id.';');
if(!$query){
exit('<h1>資料庫查詢失敗</h1>');
}
header('Location: index.php');