php+Mysql单页支持不同数据结构不同查询条件查搜多表实例

news/2024/12/5 1:35:22/

 php+Mysql单页支持不同数据结构不同查询条件查搜多表实例

本来还要增加删 改 新增的,眼睛需要休息所以放弃后续制作(增删改代码已删或注释)

直接用可以用于自己多表查搜,界面还可以;有兴趣的可以自己二次开发成改删增

php"><?php
function connectDB() {
$host = "localhost";
$user = "yuyue";
$pass = "hMSdEpHsjex8S";
$dase = "yuyue";
$conn = new mysqli($host, $user, $pass, $dase);
if ($conn->connect_error) {
die(json_encode(['success' => false, 'message' => "连接失败:" . $conn->connect_error]));
}
return $conn;
}
$conn = connectDB();
// 表配置
$site = [
"kouzhao_shop" => [
"名称" => "商家信息",
"显示项" => ["id", "店铺名称", "店铺地址", "联系电话"],
"查询项" => ["店铺名称", "联系电话"],
"新增项" => ["店铺名称", "店铺地址", "联系电话"],
"可改项" => ["店铺名称", "店铺地址", "联系电话"]
],
"kouzhao_yuyue" => [
"名称" => "预约信息",
"显示项" => ["id", "姓名", "身份证号", "手机号码", "批次号"],
"查询项" => ["姓名", "身份证号", "手机号码"],
"新增项" => ["姓名", "身份证号", "手机号码"],
"可改项" => ["姓名", "身份证号", "手机号码"]
],
"kouzhao_pici" => [
"名称" => "批次信息",
"显示项" => ["id", "预约批次", "可约份数", "每份内容"],
"查询项" => ["预约批次", "可约份数", "每份内容"],
"新增项" => ["预约批次", "可约份数", "每份内容"],
"可改项" => ["预约批次", "可约份数", "每份内容"]
],
"kouzhao_user" => [
"名称" => "用户信息",
"显示项" => ["id", "用户名"],
"查询项" => ["用户名"],
"新增项" => ["用户名", "密码"],
"可改项" => ["密码"]
]
];
$act = isset($_GET['act']) ? $_GET['act'] : null;
if($act != ""){
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
// 获取请求数据
$postData = file_get_contents("php://input");
parse_str($postData, $params);
// 获取传入参数
$table = isset($params['table']) ? $params['table'] : null;
$action = isset($params['action']) ? $params['action'] : null;
$id = isset($params['id']) ? (int) $params['id'] : null;
$data = isset($params['data']) ? json_decode($params['data'], true) : [];
$keyword = isset($params['keyword']) ? $params['keyword'] : '';
$page = isset($params['page']) ? (int) $params['page'] : 1;
// 分页参数
$perPage = 10;
$offset = ($page - 1) * $perPage;
// 校验表是否存在
if (!isset($site[$table])) {
echo json_encode(["error" => "表[$table]不存在"]);
exit;
}
// 根据请求操作
switch ($action) {
case "list": // 获取数据列表
$queryFields = $site[$table]["查询项"];
$newddFields = $site[$table]["新增项"];
$columns = implode(",", $queryFields);
$where = "";
// 查询条件
if ($keyword !== '') {
$likeConditions = [];
foreach ($queryFields as $field) {
$likeConditions[] = "$field LIKE '%" . $conn->real_escape_string($keyword) . "%'";
}
$where = "WHERE " . implode(" OR ", $likeConditions);
}
// 获取总记录数
$countSql = "SELECT COUNT(*) AS total FROM $table $where";
$countResult = $conn->query($countSql);
$totalRows = $countResult->fetch_assoc()['total'];
// 查询数据
$sql = "SELECT $columns FROM $table $where LIMIT $offset, $perPage";
$result = $conn->query($sql);
if ($result) {
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode([
"data" => $rows,
"total" => $totalRows,
"perPage" => $perPage,
'filterFields' => $queryFields,
'newaddFields' => $newddFields
]);
} else {
echo json_encode(["error" => "查询失败: " . $conn->error]);
}
break;
/*
case "add": // 新增数据
$fields = $site[$table]["新增项"];
$fieldNames = implode(",", $fields);
$placeholders = implode(",", array_fill(0, count($fields), "?"));
$stmt = $conn->prepare("INSERT INTO $table ($fieldNames) VALUES ($placeholders)");
if ($stmt) {
$bindParams = [];
$bindTypes = str_repeat("s", count($fields));
$bindParams[] = &$bindTypes;
foreach ($fields as $field) {
$bindParams[] = &$data[$field];
}
call_user_func_array([$stmt, "bind_param"], $bindParams);
if ($stmt->execute()) {
echo json_encode(["success" => "新增成功"]);
} else {
echo json_encode(["error" => "新增失败: " . $stmt->error]);
}
$stmt->close();
} else {
echo json_encode(["error" => "准备语句失败: " . $conn->error]);
}
break;
case "edit": // 修改数据
$fields = $site[$table]["可改项"];
$setFields = implode(",", array_map(function ($field) {
return "$field = ?";
}, $fields));
$stmt = $conn->prepare("UPDATE $table SET $setFields WHERE id = ?");
if ($stmt) {
$bindParams = [];
$bindTypes = str_repeat("s", count($fields)) . "i";
$bindParams[] = &$bindTypes;
foreach ($fields as $field) {
$bindParams[] = &$data[$field];
}
$bindParams[] = &$id;
call_user_func_array([$stmt, "bind_param"], $bindParams);
if ($stmt->execute()) {
echo json_encode(["success" => "修改成功"]);
} else {
echo json_encode(["error" => "修改失败: " . $stmt->error]);
}
$stmt->close();
} else {
echo json_encode(["error" => "准备语句失败: " . $conn->error]);
}
break;
case "delete": // 删除数据
$stmt = $conn->prepare("DELETE FROM $table WHERE id = ?");
if ($stmt) {
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
echo json_encode(["success" => "删除成功"]);
} else {
echo json_encode(["error" => "删除失败: " . $stmt->error]);
}
$stmt->close();
} else {
echo json_encode(["error" => "准备语句失败: " . $conn->error]);
}
break;
default:
echo json_encode(["error" => "无效的操作"]);
}
*/
$conn->close();
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>管理员多表数据管理</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
line-height: 1.6;
}
.nav-bar {
display: flex;
justify-content: flex-start;
background: #007bff;
padding: 6px;
}
.nav-bar a {
color: white;
text-decoration: none;
margin-right: 15px;
padding: 4px 6px;
border-radius: 5px;
}
.nav-bar a.active {
background: #0056b3;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
background: #f8f9fa;
border-bottom: 1px solid #ddd;
flex-wrap: wrap; /* 支持换行 */
}
b {
color: red;
}
.header h1 {
margin: 0;
font-size: 24px;
color: #333;
}
.actions {
display: flex;
align-items: center;
gap: 5px;
flex-wrap: wrap; /* 支持按钮换行 */
}
.actions select,
.actions input {
padding: 8px;
font-size: 14px;
border: 1px solid #ddd;
border-radius: 5px;
width: 200px;
}
.actions button {
padding: 6px 8px;
font-size: 14px;
color: white;
background-color: #007bff;
border: 1px solid #007bff;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.actions button:hover {
background-color: #0056b3;
}
.actions button:active {
background-color: #004085;
}
@media (max-width: 768px) {
.header {
flex-direction: column; /* 小屏幕下调整布局 */
align-items: flex-start;
gap: 15px;
}
.actions {
width: 100%; /* 使操作区域独占一行 */
}
.actions select,
.actions input {
width: 100%; /* 输入框与选择框全宽 */
}
.actions button {
width: 100%; /* 按钮全宽 */
}
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
table th, table td {
border: 1px solid #ddd;
padding: 4px;
text-align: left;
}
table th {
background: #f4f4f4;
}
.form-container {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
border: 1px solid #ddd;
padding: 20px 0;
z-index: 1000;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 999;
}
.pagination {
display: flex;
justify-content: center;
margin: 20px 0;
}
.pagination button {
padding: 5px 10px;
margin: 0 5px;
border: 1px solid #ddd;
background: white;
cursor: pointer;
}
.pagination button.disabled {
background: #f8f9fa;
cursor: not-allowed;
}
</style>
</head>
<body>
<!-- 顶部导航 -->
<div class="nav-bar" id="nav-bar">
<!-- 动态生成的表导航 -->
</div>
<!-- 主内容 -->
<div class="header">
<h1 id="table-title">数据管理</h1>
<div class="actions">
<select id="filter-field"></select>
<input type="text" id="filter-keyword" placeholder="输入关键词">
<button onclick="fetchData()">搜索</button>
</div>
</div>
<!-- 数据表 -->
<table id="data-table">
<thead></thead>
<tbody></tbody>
</table>
<!-- 分页 -->
<div class="pagination" id="pagination"></div>
<!-- 遮罩层 -->
<div class="overlay" id="overlay"></div>
<script>
let currentTable = "";
let currentPage = 1;
let totalPages = 1;
// 配置导航
const site = {
"kouzhao_shop": "商家信息",
"kouzhao_pici": "批次信息",
"kouzhao_yuyue": "预约信息",
"kouzhao_user": "用户信息"
};
// 初始化页面
window.onload = function () {
initNavBar();
loadTable(Object.keys(site)[0]);
};
// 初始化导航栏
function initNavBar() {
const navBar = document.getElementById("nav-bar");
navBar.innerHTML = "";
for (let table in site) {
const link = document.createElement("a");
link.textContent = site[table];
link.href = "#";
link.onclick = () => loadTable(table);
link.id = `nav-${table}`;
navBar.appendChild(link);
}
}
// 加载表格
function loadTable(table) {
currentTable = table;
currentPage = 1;
document.getElementById("table-title").textContent = site[table];
document.querySelectorAll(".nav-bar a").forEach(a => a.classList.remove("active"));
document.getElementById(`nav-${table}`).classList.add("active");
fetchData();
}
// 获取数据
function fetchData() {
const filterField = document.getElementById("filter-field").value || "";
const filterKeyword = document.getElementById("filter-keyword").value || "";
const url = "?act=do";
const params = {
table: currentTable,
action: "list",
keyword: filterKeyword,
page: currentPage
};
postRequest(url, params, (response) => {
renderTable(response.data);
renderPagination(response.total, response.perPage);
updateFilterFields(response.filterFields);
});
}
function updateFilterFields(fields) {
const filterFieldSelect = document.getElementById("filter-field");
filterFieldSelect.innerHTML = ""; // 清空现有选项
if (fields && fields.length > 0) {
fields.forEach(field => {
const option = document.createElement("option");
option.value = field;
option.textContent = field;
filterFieldSelect.appendChild(option);
});
}
}
// 渲染表格
function renderTable(data) {
const filterField = document.getElementById("filter-field").value || "";
const filterKeyword = document.getElementById("filter-keyword").value || "";
const table = document.getElementById("data-table");
table.tHead.innerHTML = "";
table.tBodies[0].innerHTML = "";
if (!data || data.length === 0) {
const row = document.createElement("tr");
const cell = document.createElement("td");
cell.colSpan = 5;
cell.innerHTML = "暂无<b>"+filterField+"</b>=<b>"+filterKeyword+"</b>数据";
row.appendChild(cell);
table.tBodies[0].appendChild(row);
return;
}
const fields = Object.keys(data[0]);
const headRow = document.createElement("tr");
fields.forEach(field => {
const th = document.createElement("th");
th.textContent = field;
headRow.appendChild(th);
});
table.tHead.appendChild(headRow);
data.forEach(row => {
const tr = document.createElement("tr");
fields.forEach(field => {
const td = document.createElement("td");
td.textContent = row[field];
tr.appendChild(td);
});
table.tBodies[0].appendChild(tr);
});
}
// 渲染分页
function renderPagination(total, perPage) {
totalPages = Math.ceil(total / perPage);
const pagination = document.getElementById("pagination");
pagination.innerHTML = "";
const addButton = (text, disabled, onClick) => {
const button = document.createElement("button");
button.textContent = text;
button.disabled = disabled;
button.className = disabled ? "disabled" : "";
button.onclick = onClick;
pagination.appendChild(button);
};
addButton("上一页", currentPage === 1, () => changePage(currentPage - 1));
addButton("下一页", currentPage === totalPages, () => changePage(currentPage + 1));
}
// 改变页码
function changePage(page) {
if (page > 0 && page <= totalPages) {
currentPage = page;
fetchData();
}
}
// 通用POST请求
function postRequest(url, params, callback) {
const xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = () => callback(JSON.parse(xhr.responseText));
xhr.send(Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join("&"));
}
</script>
</body>
</html>

 


http://www.ppmy.cn/news/1551233.html

相关文章

java jvm部分命令 ~~还在完善中

命令整理 jps -q 只输出进程号 -m main 函数的参数 -l 主类全名 -v 输出jvm参数 jstat jstat -gc pid 1000 10 class gc gccapacity gcutil gccause gcnew gcnewcapacity gcold gcoldcapacity compiler printcompilation gcmetacapacity jinfo -sysprops pid -flags pid -flag…

# issue 7 TCP回声服务器和客户端

一、TCP/IP协议栈 为什么需要理解协议栈&#xff1f; 学习C/C就是要懂底层的原理。不然永远是“调包侠” 根据数据传输方式的不同&#xff0c;基于网络协议&#xff08;这里是指基于TCP/IP协议&#xff09;的套接字一般分为TCP 套接字和UDP 套接字。因为TCP 套接字是面向连接的…

【docker集群应用】Docker数据管理与镜像创建

文章目录 Docker数据管理数据卷&#xff08;Data Volumes&#xff09;示例 数据卷容器&#xff08;Data Volume Containers&#xff09;示例 端口映射容器互联 Docker镜像的创建方法基于现有镜像创建1.首先启动一个镜像&#xff0c;在容器里做修改2.然后将修改后的容器提交为新…

linux实时操作系统xenomai看门狗(watchdog)机制及作用介绍

版权声明&#xff1a;本文为本文为博主原创文章&#xff0c;转载请注明出处 https://www.cnblogs.com/wsg1100。如有错误&#xff0c;欢迎指正。 文章目录 一、前言PREEMPT-RT&#xff08;RT Throttling&#xff09; 一、xenomai watchdog介绍二、xenomai watchdog工作原理三、…

Flink四大基石之State

State state 可以理解为-- 历史计算结果 有状态计算和无状态计算 无状态计算: 不需要考虑历史数据, 相同的输入,得到相同的输出!如:map, 将每个单词记为1, 进来一个hello, 得到(hello,1),再进来一个hello,得到的还是(hello,1) 有状态计算: 需要考虑历史数据, 相同的输入,可…

T507 buildroot linux4.9之RTC8563开发调试

文章目录 前言一、硬件确认1.1、RTC8563硬件二、驱动配置2.1、驱动位置2.2、使用config宏配置驱动2.3、DTS配置三、断电重启时间不保存分析四、解决问题五、测试前言 调试T507的RTC8563,解决中调试遇到的问题 一、硬件确认 1.1、RTC8563硬件 通过原理图确认 RTC8563 硬件的…

2024年12月可以报考的人工智能证书

《新质技术之第九期生成式AI、大模型、多模态技术开发与应用研修班》 2024年12月13日 — 2024年12月17日 杭州&#xff08;同时转线上直播&#xff09; &#xff08;13日报到发放上课材料&#xff0c;14日-17日上课&#xff09;

从零开发操作系统-聊一聊C语言中的头文件

你好&#xff0c;我是 shengjk1&#xff0c;多年大厂经验&#xff0c;努力构建 通俗易懂的、好玩的编程语言教程。 欢迎关注&#xff01;你会有如下收益&#xff1a; 了解大厂经验拥有和大厂相匹配的技术等 希望看什么&#xff0c;评论或者私信告诉我&#xff01; 文章目录 一…