PHP是一种广泛使用的开源脚本语言,尤其适用于Web开发。它可以嵌入HTML中,用来创建动态交互式的网页。数据库登录注册是Web应用中的基本功能之一,通常涉及到用户信息的验证和存储。
原因:
解决方案:
以下是一个简单的PHP登录注册示例:
<?php
// 数据库连接
$servername = "localhost";
$username = "dbuser";
$password = "dbpass";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 注册
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// 登录
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row["password"])) {
echo "登录成功";
} else {
echo "密码错误";
}
} else {
echo "用户名不存在";
}
}
$conn->close();
?>
<!-- 登录注册表单 -->
<form method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" name="register" value="Register">
<input type="submit" name="login" value="Login">
</form>
请注意,上述代码仅为示例,实际应用中需要考虑更多的安全措施,如防止SQL注入、XSS攻击等。
领取专属 10元无门槛券
手把手带您无忧上云