温馨提示×

怎样用Layui简化MySQL增删改查

小樊
84
2024-10-02 17:09:34
栏目: 云计算

Layui是一个前端UI框架,它可以帮助我们快速构建网页界面,但它本身并不提供数据库操作功能。要使用Layui简化MySQL的增删改查,你需要结合后端编程语言(如PHP、Python、Node.js等)来实现。以下是一个简单的示例,使用PHP和Layui实现MySQL的增删改查操作。

  1. 创建MySQL数据库表

首先,在MySQL中创建一个名为user的表,用于存储用户信息。

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. 创建PHP文件

创建一个名为index.php的文件,用于处理前端发送的请求并与MySQL数据库进行交互。

<?php
// 连接MySQL数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
  die("连接失败: " . $conn->connect_error);
}

// 获取前端发送的请求参数
$action = isset($_GET['action']) ? $_GET['action'] : '';
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';

// 根据请求参数执行相应的MySQL操作
switch ($action) {
  case 'add':
    $sql = "INSERT INTO user (username, password, email) VALUES ('$username', '$password', '$email')";
    break;
  case 'delete':
    $sql = "DELETE FROM user WHERE id=$id";
    break;
  case 'update':
    $sql = "UPDATE user SET username='$username', password='$password', email='$email' WHERE id=$id";
    break;
  case 'select':
    $sql = "SELECT * FROM user";
    break;
  default:
    echo "无效的请求参数";
    exit;
}

if ($conn->query($sql) === TRUE) {
  echo "操作成功";
} else {
  echo "错误: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
  1. 创建Layui前端页面

创建一个名为index.html的文件,用于显示表格和表单,并发送请求到后端PHP文件。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Layui简化MySQL增删改查示例</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui/css/layui.css" media="all">
</head>
<body>

<div class="layui-container">
  <div class="layui-row">
    <div class="layui-col-xs12">
      <form class="layui-form" action="">
        <div class="layui-form-item">
          <label class="layui-form-label">用户名</label>
          <div class="layui-input-block">
            <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">密码</label>
          <div class="layui-input-block">
            <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">邮箱</label>
          <div class="layui-input-block">
            <input type="email" name="email" required lay-verify="required" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <button type="button" class="layui-btn" id="add">添加</button>
            <button type="button" class="layui-btn" id="delete">删除</button>
            <button type="button" class="layui-btn" id="update">更新</button>
            <button type="button" class="layui-btn" id="select">查询</button>
          </div>
        </div>
      </form>
    </div>
  </div>
  <table class="layui-hide" id="userTable" lay-filter="userTableFilter"></table>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/layui/layui.all.js"></script>
<script>
layui.use(['form', 'table'], function(){
  var form = layui.form;
  var table = layui.table;

  // 渲染表格
  table.render({
    elem: '#userTable',
    url: 'index.php', // 数据接口
    page: true, // 开启分页
    cols: [[ // 表头
      {field: 'id', title: 'ID', sort: true},
      {field: 'username', title: '用户名', sort: true},
      {field: 'password', title: '密码', sort: true},
      {field: 'email', title: '邮箱', sort: true},
      {fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
    ]]
  });

  // 监听工具条
  table.on('tool(userTableFilter)', function(obj){
    var data = obj.data;
    if(obj.event === 'delete'){
      layer.confirm('真的删除行么', function(index){
        obj.del();
        layer.close(index);
        // 发送删除请求到后端
        $.post('index.php', {action: 'delete', id: data.id}, function(response) {
          if (response === '操作成功') {
            layer.msg('删除成功');
          } else {
            layer.msg('删除失败');
          }
        });
      });
    } else if(obj.event === 'update'){
      // 发送更新请求到后端
      $.post('index.php', {action: 'update', id: data.id, username: data.username, password: data.password, email: data.email}, function(response) {
        if (response === '操作成功') {
          layer.msg('更新成功');
        } else {
          layer.msg('更新失败');
        }
      });
    } else if(obj.event === 'select'){
      // 发送查询请求到后端
      $.post('index.php', {action: 'select'}, function(response) {
        // 将查询结果填充到表格中
        var html = '';
        response.forEach(function(item) {
          html += '<tr>';
          html += '<td>' + item.id + '</td>';
          html += '<td>' + item.username + '</td>';
          html += '<td>' + item.password + '</td>';
          html += '<td>' + item.email + '</td>';
          html += '<td><button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button></td>';
          html += '<td><button class="layui-btn layui-btn-xs layui-btn-warning" lay-event="update">更新</button></td>';
          html += '</tr>';
        });
        $('#userTable').html(html);
      });
    }
  });

  // 监听添加按钮
  $('#add').on('click', function(){
    layer.prompt({
      title: '请输入用户信息',
      formType: 1,
      value: ''
    }, function(value, index){
      $.post('index.php', {action: 'add', username: value.username, password: value.password, email: value.email}, function(response) {
        if (response === '操作成功') {
          layer.msg('添加成功');
          layer.close(index);
          table.reload('userTable'); // 刷新表格
        } else {
          layer.msg('添加失败');
        }
      });
    });
  });
});
</script>

</body>
</html>

现在,你可以在浏览器中打开index.html文件,尝试使用Layui简化MySQL的增删改查操作。请注意,这个示例仅用于演示目的,实际项目中你可能需要考虑更多的安全性和错误处理。

0