php实现数据登记
PHP 数据登记实现方法
数据库连接配置
创建一个配置文件存储数据库连接信息,通常命名为config.php:
<?php
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
创建HTML表单
设计用户输入界面,文件可命名为registration_form.html:
<form action="process_registration.php" method="post">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" required>
<label for="phone">电话:</label>
<input type="tel" id="phone" name="phone">
<input type="submit" value="提交">
</form>
处理表单数据
创建处理脚本process_registration.php:

<?php
require 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$sql = "INSERT INTO registrations (name, email, phone) VALUES (:name, :email, :phone)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':phone', $phone);
try {
$stmt->execute();
echo "登记成功!";
} catch(PDOException $e) {
echo "错误: " . $e->getMessage();
}
}
?>
数据验证
在数据处理前加入验证逻辑:
$name = trim($_POST['name']);
if (empty($name)) {
die("姓名不能为空");
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
die("邮箱格式无效");
}
防止SQL注入
使用预处理语句(如上例所示)并过滤输入:

$name = htmlspecialchars(strip_tags($_POST['name']));
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
数据库表结构
MySQL创建表的基本语句:
CREATE TABLE registrations (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone VARCHAR(20),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
错误处理
增强错误处理机制:
set_error_handler(function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
try {
// 数据库操作代码
} catch(Exception $e) {
error_log($e->getMessage());
header("HTTP/1.1 500 Internal Server Error");
exit("系统错误,请稍后再试");
}
文件上传处理
如需处理文件上传:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["photo"]["name"]);
if (move_uploaded_file($_FILES["photo"]["tmp_name"], $target_file)) {
$photo_path = $target_file;
}
}






