php游戏网站注册代码
时间: 2024-09-15 21:02:57 浏览: 25
基于php写小游戏代码
创建一个PHP游戏网站的用户注册功能涉及几个关键步骤,包括数据验证、表单处理和数据库操作。下面是一个简单的示例,展示了如何处理注册过程的基本结构:
```php
<?php
// 连接数据库 (假设已配置好数据库连接)
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myGameDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 用户注册表单处理
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// 数据验证
if (empty($username) || empty($email)) {
echo "所有字段都是必需的!";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "无效的电子邮件地址!";
} else {
// 验证用户名是否唯一
$sql = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "用户名已经存在!";
} else {
// 将数据插入到数据库
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
if ($conn->query($sql) === TRUE) {
echo "新用户注册成功!";
} else {
echo "错误: " . $sql . "<br>" . $conn->error;
}
}
}
}
// 注册表单 HTML
echo "
<form action='register.php' method='post'>
<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>
<input type='submit' value='注册'>
</form>";
$conn->close();
?>
```
阅读全文