我对使用 MySql 很陌生,并且在从数据库中检索值时遇到问题。我的印象是我以正确的方式去做,但我的回声语句没有打印任何东西。
我将不胜感激。我的代码如下。我知道我以后必须添加安全性,例如清理用户输入。
<?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 检查该条目是否存在,然后检索用户数据。