gpt4 book ai didi

php - 为什么这个 PHP 代码不正确?

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:58 25 4
gpt4 key购买 nike

这是显示必须在我的登录系统中显示的错误的代码:

<?php

include 'session.php';

if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];

if (empty($username) === true || empty($password) === true) {
$errors[] = 'Please enter a username and password.';
} else if (user_exists($username) === false) {
$errors[] = 'The username or password is incorrect.';
}
print_r($errors);
}

?>

这是对数据库执行查询的代码,我在上面的代码中使用的函数“user_exists”。

<?php

function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(customerNumber) FROM customers WHERE username = '$username'"), 0) == 1) ? true : false;
}

?>

因此,当用户名/密码组合错误时,login.php 显然应该显示“用户名或密码不正确”。但是,当我尝试使用正确的用户名和密码(来 self 的数据库)登录时,它还会显示“用户名或密码不正确。”。那么这段代码有什么问题呢?

最佳答案

如果我正确理解你的问题,这一行让你成为真正的问题,它总是从这里返回 false 因为你的客户 count0 行不等于1,所以每次都返回false

return (mysql_result(mysql_query("
SELECT COUNT(customerNumber) FROM customers WHERE
username = '$username'"), 0) == 1) ? true : false;

来自 PHP 手册用户注释

mysql_result() will throw E_WARNING if mysql_query returns 0 rows. This is unlike any of the mysql_fetch_* functions so be careful of this if you have E_WARNING turned on in error_reporting(). You might want to check mysql_num_rows() before calling mysql_result()

根据评论:

 function user_exists($username) {
$username = sanitize($username);
$result=mysql_result(mysql_query("SELECT COUNT(customerNumber) FROM customers WHERE username = '$username'"), 0);
print $result; //see what it returns
die(); //remove this line after your debugging.
return ($result == 1) ? true : false;
}

关于php - 为什么这个 PHP 代码不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29923939/

25 4 0
文章推荐: python - Tensorflow:__new__() 在对象检测 API 中得到了一个意外的关键字参数 'serialized_options'
文章推荐: c# - 如何使用 MSAL 在控制台应用程序中代表用户获取访问 token 以调用 MS Graph?
文章推荐: c# - 从 Razor 页面发送 List 到 Update 的行?