gpt4 book ai didi

php - 验证 MySQL 的登录详细信息

转载 作者:行者123 更新时间:2023-11-29 08:25:10 26 4
gpt4 key购买 nike

我目前正在开发自己的 CMS。

由于某种原因,它似乎不接受我的登录详细信息...代码是:

<?php

session_start();

include_once('../includes/connection.php');

if (isset($_SESSION['logged_in'])) {
// display index
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);

if (empty($username) or empty($password)){
$error = 'Please enter all of the fields!';
} else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_password = ?");

$query->bindValue(1, $username);
$query->bindValue(2, $password);

$query->execute();

$num = $query->rowCount();

if ($num == 1) {
// user entered correct
$_SESSION['logged_in'] = true;

header('Location: index.php');
exit();
} else {
//user entered false
$error = "Incorrect details!";
}
}
}
?>

<html>
<head>
<title>CMS</title>
<link rel="stylesheet" type="text/css" href="../assets/style.css" />
</head>

<body>
<div class="container">
<a href="index.php" id="logo">CMS</a>

<br /><br />

<?php if (isset($error)) { ?>

<small style="color:#aa0000;">
<?php echo $error; ?>
<br /><br />
</small>

<?php } ?>

<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>

</div>
</body>
</html>

<?php
}

?>

连接是:

> <?php
>
> try { $pdo = new PDO('mysql:host=localhost;dbname=website', 'root',
> ''); } catch (PDOException $se) { exit('Database error.'); }
>
>
> ?>

每次我尝试使用正确的详细信息登录时,它只会显示“详细信息不正确”

有什么想法吗?

最佳答案

您正在检查查询是否返回结果。然而,您这样做的方式不适用于 SELECT 查询。它用于例如删除。

试试这个:

<?php
if ($res = $conn->query($sql))
{
if ($res->fetchColumn() > 0)
{
// user entered correct
}
else
{
//user entered false
}
}

有关此内容的更多信息可以在 PHP Manual 中找到。 .

我想添加手册中的这句话:

For most databases, PDOStatement::rowCount() does not return thenumber of rows affected by a SELECT statement. Instead, usePDO::query() to issue a SELECT COUNT(*) statement with the samepredicates as your intended SELECT statement, then usePDOStatement::fetchColumn() to retrieve the number of rows that willbe returned. Your application can then perform the correct action.

关于php - 验证 MySQL 的登录详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18165697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com