当前位置: 首页 > news >正文

PHP+Vue 3实现增删改查(CRUD)

后端(PHP)

首先,我们需要一个简单的PHP后端来处理增删改查操作。假设我们有一个名为items的表,包含idnamedescription字段。

1. 数据库连接

创建一个db.php文件来处理数据库连接:

<?php
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_username';
$password = 'your_password';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Could not connect to the database $dbname :" . $e->getMessage());
}
?>
2. CRUD操作

创建一个api.php文件来处理CRUD操作:

<?php
require 'db.php';

header("Content-Type: application/json; charset=UTF-8");

$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'], '/'));

if ($request[0] === 'items') {
    switch ($method) {
        case 'GET':
            if (isset($request[1])) {
                $stmt = $pdo->prepare("SELECT * FROM items WHERE id = ?");
                $stmt->execute([$request[1]]);
                $item = $stmt->fetch(PDO::FETCH_ASSOC);
                echo json_encode($item);
            } else {
                $stmt = $pdo->query("SELECT * FROM items");
                $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
                echo json_encode($items);
            }
            break;
        case 'POST':
            $data = json_decode(file_get_contents("php://input"), true);
            $stmt = $pdo->prepare("INSERT INTO items (name, description) VALUES (?, ?)");
            $stmt->execute([$data['name'], $data['description']]);
            echo json_encode(['id' => $pdo->lastInsertId()]);
            break;
        case 'PUT':
            $data = json_decode(file_get_contents("php://input"), true);
            $stmt = $pdo->prepare("UPDATE items SET name = ?, description = ? WHERE id = ?");
            $stmt->execute([$data['name'], $data['description'], $request[1]]);
            echo json_encode(['success' => true]);
            break;
        case 'DELETE':
            $stmt = $pdo->prepare("DELETE FROM items WHERE id = ?");
            $stmt->execute([$request[1]]);
            echo json_encode(['success' => true]);
            break;
    }
}
?>

前端(Vue 3)

接下来,我们使用Vue 3来创建一个简单的用户界面来处理增删改查操作。

1. 安装Vue 3

首先,确保你已经安装了Vue CLI。如果没有,可以使用以下命令安装:

npm install -g @vue/cli

然后创建一个新的Vue项目:

vue create vue-crud
cd vue-crud
2. 创建组件

src/components目录下创建一个ItemList.vue组件:

<template>
  <div>
    <h1>Items</h1>
    <ul>
      <li v-for="item in items" :key="item.id">
        {{ item.name }} - {{ item.description }}
        <button @click="editItem(item)">Edit</button>
        <button @click="deleteItem(item.id)">Delete</button>
      </li>
    </ul>
    <form @submit.prevent="addItem">
      <input v-model="newItem.name" placeholder="Name" required />
      <input v-model="newItem.description" placeholder="Description" required />
      <button type="submit">Add Item</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      items: [],
      newItem: { name: '', description: '' },
    };
  },
  methods: {
    async fetchItems() {
      const response = await axios.get('http://localhost/api.php/items');
      this.items = response.data;
    },
    async addItem() {
      const response = await axios.post('http://localhost/api.php/items', this.newItem);
      this.items.push({ id: response.data.id, ...this.newItem });
      this.newItem = { name: '', description: '' };
    },
    async editItem(item) {
      const updatedName = prompt('Enter new name', item.name);
      const updatedDescription = prompt('Enter new description', item.description);
      if (updatedName && updatedDescription) {
        await axios.put(`http://localhost/api.php/items/${item.id}`, {
          name: updatedName,
          description: updatedDescription,
        });
        item.name = updatedName;
        item.description = updatedDescription;
      }
    },
    async deleteItem(id) {
      await axios.delete(`http://localhost/api.php/items/${id}`);
      this.items = this.items.filter(item => item.id !== id);
    },
  },
  created() {
    this.fetchItems();
  },
};
</script>
3. 在主应用中使用组件

src/App.vue中使用ItemList组件:

<template>
  <div id="app">
    <ItemList />
  </div>
</template>

<script>
import ItemList from './components/ItemList.vue';

export default {
  name: 'App',
  components: {
    ItemList,
  },
};
</script>
4. 运行应用

最后,运行Vue应用:

npm run serve

现在,你应该能够在浏览器中访问http://localhost:8080,并看到一个简单的增删改查界面。

总结

这个示例展示了如何使用PHP和Vue 3实现一个基本的增删改查功能。你可以根据需要扩展这个示例,例如添加表单验证、分页、排序等功能。

相关文章:

  • 网络安全小知识课堂(十二)
  • Java:学习进阶之路
  • 使用 JSON Schema 实现语言模型的结构化输出:跨平台实践指南
  • git clone(复制)下载
  • Nginx 499 错误的原因及解决方法
  • OpenCV--模板匹配
  • 使用Docker Desktop进行本地打包和推送
  • Kafka分区机制详解:原理、策略与应用
  • Docker+Jenkins+Gitee自动化项目部署
  • 详解 Redis repl_backlog_buffer(如何判断增量同步)
  • 2025年智能 ITSM产品推荐
  • Elasticsearch | ES索引模板、索引和索引别名的创建与管理
  • “图生生”AI生图优化升级,DeepSeek加持体验更优!
  • SAN及其ZONE
  • 【kind管理脚本-2】脚本使用说明文档 —— 便捷使用 kind 创建、删除、管理集群脚本
  • JavaScript学习教程,从入门到精通,JavaScript 数据类型详解(7)
  • 《AI开发工具和技能实战》专栏规划:从工具到应用的全链路指南
  • IntelliJ IDEA使用技巧(json字符串格式化)
  • vue3+vue-router4的安装使用以及路由守卫
  • Android audio(2)-audioservice
  • 深圳电子商务网站制作/网络宣传方案
  • 怎么给新网站做推广/网站设计需要什么
  • 企业微信有哪些功能/关键词优化报价查询
  • 娄底网站建设79ld/搜索量查询百度指数
  • 自做网站的步骤/宁波seo推广服务
  • 成都科技网站建设联系电话/广告投放公司