我想创建一个PHP登录脚本,当用户登录时,它会删除登录表单,另一个div表示"欢迎[user_name]"。我在与html相同的页面上运行脚本,但查询总是失败。任何人都可以解决这个问题,为什么会发生这种情况?
PHP代码:
<?php include("connect.php")?>
<?php
session_start();
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
if(isset($_POST['username']) && isset($_POST['username'])){
//Sanitize the POST values
$UserName = clean($_POST['username']);
$Password =(md5($_POST['password']));
//Create query
$qry = "SELECT 'UserName' , 'Password' FROM users WHERE UserName='$UserName' AND Password='$Password'";
$result = mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['FName'];
$_SESSION['SESS_LAST_NAME'] = $member['LName'];
//session_write_close();
echo 'SUCCESS';
//loggedin();
//exit();
}
else {
//Login failed
echo 'FAILED.';
//loginfail();
//exit();
}
}
else {
die("Query failed");
}
}
?>
HTML CODE:
<form name="user-form" id="user-form" action="members.php" method="POST">
<input type="text" name="username" id="username" placeholder="Username"></input>
<input type="password" name="password" id="password" placeholder="Password"></input>
<br/>
<input type="submit" id="sign" name="Sign In"></input>
</form>
我很高兴为您提供帮助。
答案 0 :(得分:0)
这是错误的 -
SELECT 'UserName' , 'Password'....
删除'
并替换为
还要正确处理字符串,只需用 -
WHERE UserName='$UserName' AND Password='$Password'"
WHERE UserName=\"".$UserName."\" AND Password=\"".$Password."\""
所以完整的查询将是 -
"SELECT `UserName` , `Password` FROM users WHERE UserName=\"".$UserName."\" AND Password=\"".$Password."\""
(还要记住列名称区分大小写)
答案 1 :(得分:0)
此:
$qry = "SELECT 'UserName' , 'Password' FROM users WHERE UserName='$UserName' AND Password='$Password'";
应该是:
$qry = "SELECT username , password FROM users WHERE UserName='$UserName' AND Password='$Password'";