php+mysql簡單的添加和刪除小案例

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="#">&laquo;</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="#">&raquo;</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');

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章