gpt4 book ai didi

php - 从 MySQL 数据库检索值时遇到问题

转载 作者:行者123 更新时间:2023-11-29 14:24:18 24 4
gpt4 key购买 nike

我对使用 MySql 非常陌生,并且在从数据库中检索值时遇到问题。我的印象是我正在以正确的方式处理它,但我的 echo 语句没有打印任何内容。

我希望得到一些帮助。我的代码如下。我知道稍后我必须添加安全性,例如清理用户输入。

<?php
$email = $_POST['email'];
$password = $_POST['password'];
$hashedPass = sha1($password);

if ((!isset($email)) || (!isset($password))) {
//Visitor needs to enter a name and password
echo "Data not provided";
} else {
echo "Received details $email and $password <br/>";
// connect to mysql
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
echo "Connected to phpmyadmin <br/>";
}
}
// select the appropriate database
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
echo "Cannot select database.";
exit;
} else {
echo "DB Selected";
}
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashedPass."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
echo "Cannot run query.";
exit;
}

$row = mysqli_fetch_row($result);
$count = $row[0];

$userdata = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $userdata[3];
echo $userdata['firstName'];

if ($count > 0) {
echo "<h1>Login successful!</h1>";
echo "<p>Welcome.</p>";
echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
// visitor's name and password combination are not correct
echo "<h1>Login unsuccessful!</h1>";
echo "<p>You are not authorized to access this system.</p>";
}
?>

最佳答案

我认为问题在于您调用了两次 *fetch* 系列函数,这将导致 $userdata 为空。

来自文档mysql_fetch_row将获取下一行并将内部数据指针向前移动。因此,当您调用 mysqli_fetch_array($result, MYSQLI_BOTH) 并且我认为用户/密码是唯一的时,没有任何内容可检索。您犯的另一个错误是您的 SELECT 不检索实际的用户数据,而只是检索用户/密码组合的计数。因此,即使您正确获取数据,您的用户数据也将始终不正确。

因此将您的查询更改为类似的内容:

 $query = "select * from user where email = '".$email."' and password = '".$hashedPass."' LIMIT 1";

然后使用mysql_fetch_array检查条目是否存在,然后检索用户数据。

关于php - 从 MySQL 数据库检索值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11282597/

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