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');

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页