PHP+MySQL+Ajax实现注册功能

发布时间:2024年01月07日

本文使用原生PHP和mysql数据库,使用jquery的ajax实现注册功能。

注册页面

注册页面由,html表

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户注册页面</title>
    <style>
		.container {
		    width: 300px;
		    margin: auto;
		    padding: 20px;
		    border: 1px solid #ccc;
		    border-radius: 5px;
		}

		input[type="text"], input[type="email"], input[type="password"] {
		    width: 100%;
		    padding: 12px 20px;
		    margin: 8px 0;
		    display: inline-block;
		    border: 1px solid #ccc;
		    box-sizing: border-box;
		}

		button {
		    background-color: #4CAF50;
		    color: white;
		    padding: 14px 20px;
		    margin: 8px 0;
		    border: none;
		    cursor: pointer;
		    width: 100%;
		    border-radius: 5px;
		}

		button:hover {
		    opacity: 0.8;
		}

		#message {
		    color: red;
		}
    </style>
    <script src="jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <h2>用户注册</h2>
        <form id="registerForm">
            <label for="username">用户名:</label>
            <input type="text" id="username" name="username" required>
            <br>
            <label for="email">邮箱:</label>
            <input type="email" id="email" name="email" required>
            <br>
            <label for="password">密码:</label>
            <input type="password" id="password" name="password" required>
            <br>
            <button type="submit">注册</button>
        </form>
        <p id="message"></p>
    </div>
    <script>
		document.getElementById('registerForm').addEventListener('submit', function(event) {
		    event.preventDefault();
		    
		    var username = document.getElementById('username').value;
		    var email = document.getElementById('email').value;
		    var password = document.getElementById('password').value;

		    if (!validateUsername(username) || !validateEmail(email) || !validatePassword(password)) {
		        document.getElementById('message').innerText = '请检查您的输入信息是否正确';
		        return;
		    }
		    
		    // 这里可以添加发送请求到服务器进行实际的注册操作
		    $.ajax({
		        url: 'register.php',
		        method: 'POST',
		        data: {username: username, password: password, email: email},
		        dataType: 'json',
		        success: function(response) {
		            if(response.status == 'success') {
		                alert('注册成功');
		                // 处理请求成功后的操作
        				//window.location.href = "yourRedirectUrl"; // 页面跳转到需要的 URL
		            } else {
		                alert('注册失败:' + response.message);
		            }
		        },
		        error: function(xhr, status, error) {
		            console.log('Error: ' + xhr.responseText);
		        }
		    });
		    // 模拟注册成功后的提示
		    // document.getElementById('message').innerText = '注册成功!';

		    // 清空表单
		    this.reset();
		});

		function validateUsername(username) {
		    // 实际中应包含更复杂的验证逻辑,这里仅作简单示例
		    return username.length > 0;
		}

		function validateEmail(email) {
		    // 使用正则表达式进行邮箱格式验证
		    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
		    return re.test(email);
		}

		function validatePassword(password) {
		    // 实际中应包含更复杂的验证逻辑,比如长度、特殊字符等,这里仅作简单示例
		    return password.length > 0;
		}
    </script>
</body>
</html>

创建数据库sql

创建数据库

CREATE DATABASE db100;

创建数据表

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(255) DEFAULT NULL,
  `regtime` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

数据库连接文件

<?php 
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "db100";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
 ?>

注册PHP文件

<?php

include 'conn.php';
// 获取前端传来的数据
$username = $_POST['username'];
// $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // 对密码进行哈希加密
$password = $_POST['password'];
$email = $_POST['email'];

// 验证输入并尝试插入数据
$sql = "INSERT INTO user (username, password, email)
VALUES (?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $username, $password, $email);

if ($stmt->execute()) {
    echo json_encode(array('status' => 'success'));
} else {
    echo json_encode(array('status' => 'error', 'message' => '注册失败,请检查您的输入或稍后再试.'));
}

$stmt->close();
$conn->close();
?>
文章来源:https://blog.csdn.net/qq_23488347/article/details/135443187
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。