【发布时间】:2016-06-04 13:44:36
【问题描述】:
我试图在 php 中显示错误消息($error="用户名或密码无效"; ) 当用户名或密码不在数据库中时。但是甚至没有运行代码(在 index.php 中单击登录,就会显示错误消息。谢谢 :)
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
}
if (isset($_POST['submit'])) {
// Define $username and $password
$name=$_POST['username'];
$pass=$_POST['password'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password FROM login";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["password"]. "<br>";
if($name==$row["username"] && $pass== $row["password"]){
header("location: profile.php"); // Redirecting To Other Page
}else{
$error="Username or Password is invalid";
}
}
}
else {
echo "Server is down";
}
$conn->close();
}
?>
我的 index.php
<?php
include('../php/login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: ../php/profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
【问题讨论】:
-
所以即使您干净地打开页面而不是更新它,您也会看到错误?顺便说一句,这是非常不安全的,你应该为你的 sql 使用准备好的语句。
-
我尝试关闭服务器并重新打开它,谢谢。