上一篇
html数据库代码
- 行业动态
- 2025-04-29
- 4975
HTML需结合后端语言(如PHP)连接数据库,通过SQL查询获取数据
数据库连接配置
使用后端语言(如PHP、Node.js)连接数据库,以下为PHP连接MySQL示例:
文件 | 代码示例 |
---|---|
config.php | “`php |
$host = ‘localhost’;
$user = ‘root’;
$password = ‘123456’;
$db = ‘test_db’;
$conn = new mysqli($host, $user, $password, $db);
if ($conn->connect_error) {
die(“连接失败: ” . $conn->connect_error);
}
---
HTML展示数据库数据
通过PHP从数据库读取数据,嵌入HTML表格:
| 文件 | 代码示例 |
|----------|---------------|
| `index.php` | ```php
<?php
require 'config.php';
$result = $conn->query("SELECT FROM users");
?>
<table border="1">
<tr><th>ID</th><th>姓名</th><th>年龄</th></tr>
<?php while($row = $result->fetch_assoc()): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['name'] ?></td>
<td><?= $row['age'] ?></td>
</tr>
<?php endwhile; ?>
</table>
``` |
---
HTML表单提交数据到数据库
通过HTML表单收集数据,后端插入数据库:
| 文件 | 代码示例 |
|----------|---------------|
| `add.php` | ```html
<form action="insert.php" method="POST">
姓名: <input type="text" name="name"><br>
年龄: <input type="number" name="age"><br>
<button type="submit">提交</button>
</form>
``` |
| `insert.php` | ```php
<?php
require 'config.php';
$name = $conn->real_escape_string($_POST['name']);
$age = $conn->real_escape_string($_POST['age']);
$sql = "INSERT INTO users (name, age) VALUES ('$name', $age)";
if ($conn->query($sql) === TRUE) {
echo "数据插入成功";
} else {
echo "错误: " . $sql . "<br>" . $conn->error;
}
$conn->close();
``` |
---
数据更新与删除
在HTML表格中添加编辑/删除按钮,触发后端操作:
| 文件 | 代码示例 |
|----------|---------------|
| `index.php`(扩展) | ```php
<table border="1">
<tr><th>ID</th><th>姓名</th><th>年龄</th><th>操作</th></tr>
<?php while($row = $result->fetch_assoc()): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['name'] ?></td>
<td><?= $row['age'] ?></td>
<td>
<a href="edit.php?id=<?= $row['id'] ?>">编辑</a> |
<a href="delete.php?id=<?= $row['id'] ?>">删除</a>
</td>
</tr>
<?php endwhile; ?>
</table>
``` |
---
相关问题与解答
问题1:如何防止SQL注入攻击?
解答:
1. 使用预处理语句(Prepared Statements)或参数化查询。
```php
$stmt = $conn->prepare("INSERT INTO users (name, age) VALUES (?, ?)");
$stmt->bind_param("si", $name, $age);
$stmt->execute();
- 对用户输入进行严格过滤(如
htmlspecialchars
、intval
等)。
问题2:如何实现HTML页面数据的实时更新?
- 解答:
- AJAX轮询:定时向服务器发送请求获取最新数据。
setInterval(function() { $.get('fetch_data.php', function(data) { $('#table').html(data); }); }, 5000); // 每5秒更新一次
- WebSocket:建立长连接
- AJAX轮询:定时向服务器发送请求获取最新数据。