[英]Having trouble retrieving values from MySQL database
我對使用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檢查條目是否存在,然后檢索用戶數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.