表数据:
create table users
(
id int primary key auto_increment,
username varchar(64) unique not null,
password varchar(64) not null,
email varchar(64) not null
);
insert into users(username,password,email) values('aaa','aaa','aaa@qq.com');
insert into users(username,password,email) values('bbb','bbb','bbb@qq.com');
$sql = "select * from users where username=$username and password=$password ";
$sql = "select * from users where username='$username' and password='$password'";
没有单引号的话,当做数值处理。
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
</head>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$link = mysql_connect('localhost','root','123456');
if (!$link) {
die(mysql_error());
} else {
echo '连接成功<br/>';
}
mysql_select_db('test') or die(mysql_error());
//第一种写法
$sql = "select * from users where username='$username' and password='$password' ";
//使用万能密码,密码框输入 bb' or 1='1
//select * from users where username='aaa' and password='bb' or 1='1'
//万能用户名,
// select * from users where username='abb' union select * from users;/*
//$sql = "select * from users where username='abb' union select * from users/*\ ";
$res = mysql_query($sql,$link);
if (mysql_num_rows($res) != 0) {
//跳转到管理页面
header('Location:ManageUser.php');
} else {
echo '您输入的用户名或者密码有误' . "<a href='Login.php'>返回登陆页面</a>";
}
?>
</html>
如何解决 SQL 注入
解决方法1:
//防范防范1:密码比对
$sql = "select password from users where username='$username' ";
$res = mysql_query($sql,$link);
//取出密码
if ($row = mysql_fetch_row($res)) {
//说明该用户名存在
//var_dump($row);die;
if ($row[0] == $password) {
//该用户合法
header('Location:ManageUser.php');
} else {
echo '您输入的用户名或者密码有误' . "<a href='Login.php'>返回登陆页面</a>";
}
} else {
echo '您输入的用户名不存在' . "<a href='Login.php'>返回登陆页面</a>";
}
解决方法2:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from users where username=? and password=?";
//使用 pdo
//1.创建一个 pdo 对象
$myPdo = new PDO("mysql:host=localhost;port=3306;dbname=test",'root','123456');
//2.设置编码 utf8 没有 -
$myPdo->exec("set names utf8");
//3.预处理
$pdoStatement = $myPdo->prepare($sql);
//4.把接收到的用户名和密码绑定
$pdoStatement->execute(array($username,$password));
//5.取出结果
$res = $pdoStatement->fetch();
if (empty($res)) {
echo "你的用户名或密码有误<a href='Login.php'>返回重新登陆</a>";
} else {
header('Location:ManageUser.php');
}
?>