PHP网页操作MySQL数据库,实现增删查功能并美化页面
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>操作MySQL数据库</title>
<style>
body {
margin: 0;
padding: 20px;
font-family: Arial, sans-serif;
background-color: #f2f2f2;
}
h1 {
color: #333333;
}
table {
width: 100%;
border-collapse: collapse;
}
table th, table td {
padding: 10px;
border: 1px solid #cccccc;
}
table th {
background-color: #dddddd;
}
.add-form {
margin-bottom: 10px;
}
.add-form input[type='text'] {
padding: 5px;
width: 200px;
}
.add-form input[type='submit'] {
padding: 5px 10px;
background-color: #4caf50;
color: white;
border: none;
cursor: pointer;
}
.delete-btn {
padding: 5px 10px;
background-color: #f44336;
color: white;
border: none;
cursor: pointer;
text-decoration: none;
}
@media (max-width: 768px) {
table {
font-size: 14px;
}
}
</style>
</head>
<body>
<h1>操作MySQL数据库</h1>
<pre><code><?php
// 数据库配置
$host = '43.143.25.74';
$port = 3306;
$user = 'tuisong';
$passwd = 'xX300400';
$db = 'tuisong';
$charset = 'utf8';
// 创建数据库连接
$conn = new mysqli($host, $user, $passwd, $db, $port);
if ($conn->connect_error) {
die('数据库连接失败: ' . $conn->connect_error);
}
// 处理删除请求
if (isset($_POST['delete'])) {
$id = $_POST['delete'];
$sql = "DELETE FROM zhidemaikey WHERE id = $id";
if ($conn->query($sql) === TRUE) {
header("Location: {$_SERVER['PHP_SELF']}");
exit;
} else {
echo "删除失败: " . $conn->error;
}
}
// 处理添加请求
if (isset($_POST['add'])) {
$zdmkey = $_POST['zdmkey'];
$sql = "INSERT INTO zhidemaikey (zdmkey) VALUES ('$zdmkey')";
if ($conn->query($sql) === TRUE) {
header("Location: {$_SERVER['PHP_SELF']}");
exit;
} else {
echo "添加失败: " . $conn->error;
}
}
// 查询所有内容
$sql = "SELECT * FROM zhidemaikey";
$result = $conn->query($sql);
?>
<form class='add-form' method='post'>
<input type='text' name='zdmkey' placeholder='请输入内容' required>
<input type='submit' name='add' value='添加'>
</form>
<table>
<tr>
<th>ID</th>
<th>内容</th>
<th>操作</th>
</tr>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["zdmkey"] . "</td>";
echo "<td><a class='delete-btn' href='{$_SERVER['PHP_SELF']}?delete=" . $row["id"] . "'>删除</a></td>";
echo "</tr>";
}
} else {
echo "<tr><td colspan='3'>暂无数据</td></tr>";
}
?>
</table>
<?php
// 关闭数据库连接
$conn->close();
?>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/o6tu 著作权归作者所有。请勿转载和采集!