我是一名新手PHP开发人员,我试图研究如何在我放弃使用会话和cookie之前创建一个简单的登录
我的第一个代码有效,但我想稍微减少代码,所以我尝试了别的东西,这个错误出现了,我很好奇为什么其他代码没有工作,而他们不会似乎是那种不同的
<?php
//The code that works
include("connection.php");
$connection = mysqli_connect(Server,Uid,Pwd,Database);
if(!$connection){
die("Connection failed!" . mysqli_error($connection));
}
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($connection,$_POST['username']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
//$query = "SELECT * FROM 'user' WHERE Username = $username AND Password = $password";
$query = "SELECT * FROM user WHERE Username= '". mysqli_real_escape_string($connection,$username) ."' AND Password = '". mysqli_real_escape_string($connection,$password) ."'" ;
$result = mysqli_query($connection,$query);
$count = mysqli_num_rows($result);
if ($count == 1){
echo "Logged In Successfully! ";
}
else{
echo "Log In Failed! Invalid Username or Password! ";
}
}
?>
<?php
//The code that doesn't work
include("connection.php");
$connection = mysqli_connect(Server,Uid,Pwd,Database);
if(!$connection){
die("Connection failed!" . mysqli_error($connection));
}
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($connection,$_POST['username']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$query = "SELECT * FROM 'user' WHERE Username = $username AND Password = $password";
$result = mysqli_query($connection,$query);
$count = mysqli_num_rows($result);
if ($count == 1){
echo "Logged In Successfully! ";
}
else{
echo "Log In Failed! Invalid Username or Password! ";
}
}
?>
它们不应该是一样的,因为在代码的第二个版本中我只是将mysqli_real_escape_string放在变量的值中,那么如何调用包含mysqli_real_escape_string的$ username和$ password变量会产生这个错误?所以它总是必须像每个查询一样吗?
答案 0 :(得分:0)
1)将SELECT * FROM 'user'..
更改为SELECT * FROM user..
。单引号不允许包含表或列名称。相反,使用Backtick。
3)如果在DB中存储普通密码,则在将其保存到表之前对其进行加密。
<?php
include("connection.php");
$connection = mysqli_connect(Server, Uid, Pwd, Database);
if (!$connection) {
die("Connection failed!" . mysqli_error($connection));
}
if (isset($_POST['submit'])) {
$stmt = mysqli_prepare($connection, "SELECT * FROM `user` WHERE Username = ? AND Password = ?");
mysqli_stmt_bind_param($stmt, "ss", $_POST['username'], $_POST['password']);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt);
if ($count == 1) {
echo "Logged In Successfully! ";
} else {
echo "Log In Failed! Invalid Username or Password! ";
}
}
?>