我有这段代码:
if($submit)
{
$first=$_POST['first'];
$password=$_POST['password'];
$db = mysql_connect("localhost", "root","");
mysql_select_db("learndb",$db);
$sql = "select * from admin where username = '" . $first . "' and password = '". $password . "'";
$result = mysql_query($sql);
if($result>0)
{
echo "LOGGED IN!!";
}
else
{
echo "ERROR!!!";
}
我的html表单是:
<form method="post" action="input-copy.php">
First name:<input type="Text" name="first" placeholder="ENTER YOUR NAME"><br>
password:<input type="password" name="password" placeholder="ENTER PASSWORD"><br>
<input type="submit" name="submit" value="Enter information"></form>
但无论我输入名字和密码,它都会显示LOGGED IN!
答案 0 :(得分:4)
<强> mysql_query 强>
对于SELECT,SHOW,DESCRIBE,EXPLAIN和其他语句返回 resultset,mysql_query()在成功时返回资源,或者返回FALSE 错误。
从结果集中检索行数。
$result = mysql_query($sql);
$row = mysql_num_rows($result);
if ($row > 0) {
echo "LOGGED IN!!";
} else {
echo "ERROR!!!";
}
注意强>
使用mysqli或PDO
来删除Mysql
不要将普通密码存储到数据库中使用散列技术
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/faq.passwords.php
要防止sql注入,请检查 How can I prevent SQL injection in PHP?
答案 1 :(得分:2)
此处您的$result
变量将存储mysql_query返回值,如果您的mySQL查询正确,则为true。这也是你的逻辑登录的原因,无论密码或用户名是什么。
您需要使用mysql_num_rows检查结果计数。
试试这个:
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);//Check database table data exits...
if($num_rows == 1){
//You stuff here
}
警告强>
此扩展在PHP 5.5.0中已弃用,并已在PHP中删除 7.0.0。相反,应使用MySQLi或PDO_MySQL扩展名。
答案 2 :(得分:-1)
这是一个简单的登录代码,您可以尝试
//login query
$sql="SELECT password FROM login WHERE user_name='$username'";
$result=mysqli_query($conn ,$sql);
// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);
if($count == 1)
{
// Associative array
$row=mysqli_fetch_assoc($result);
if ($password == $row["password"]) {
$_SESSION['user'] = $username;
echo "Loggedin";
mysqli_free_result($result);
}
else
{
echo "Not a valid user";
}
}
else
{
$_SESSION["error_log"] = "No such user exist!";
header("location:../index.php");
die($_SESSION["error_log"]);
}