php使用pdo链接mysql实现登录,登录成功后转跳到user.php,显示登录的账号
时间: 2024-05-28 12:09:08 浏览: 63
可以使用以下代码实现:
<?php
// 连接数据库
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'myusername';
$password = 'mypassword';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
// 处理登录请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = $_POST['email'];
$password = $_POST['password'];
// 查询用户是否存在
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND password = ?');
$stmt->execute([$email, $password]);
$user = $stmt->fetch();
// 登录成功,跳转到用户页面
if ($user) {
header('Location: user.php');
exit;
} else {
echo 'Invalid email or password';
}
}
?>
<form method="POST">
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
阅读全文