1, create a new user table
create table user(
id int(4) not null primary key auto_increment ,
name varchar(255) not null,
pwd varchar(255) not null)
CHARSET=utf8;
2, insert test data
INSERT INTO user(name,pwd) VALUES('bobo','bobo');
3. Create a new login.php file to write the login html page.
##The code is as follows:
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/3/5 0005 * Time: 下午 1:12 */ ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="check.php" method="post"> 用户名:<input type="text" id="name" name="name"/><br> 密码:<input type="password" id="pwd" name="pwd" /><br> <input type="submit" id='login' name='login' value="登录"> </form> </body> </html>
4. Create a new check.php file to obtain form submission data for database connection processing.
The code is as follows:
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/3/5 0005 * Time: 下午 1:14 */ header('content-type:text/html;charset=utf-8'); $username=$_POST['name']; $pwd=$_POST['pwd']; try { $pdo=new PDO('mysql:host=localhost;dbname=php','root','root'); $sql="select * from user where name='{$username}' and pwd='{$pwd}'"; $stmt=$pdo->query($sql); //返回结果集中的行数 echo $stmt->rowCount(); } catch (Exception $e) { echo $e->getMessage(); }
The result of running the browser is as follows:
Enter the user name bobo, and the password bobo prints out 1
Enter the wrong username and password and print 0
Enter the injection sql statement 'or 1=1#Print is still 1, it is obvious that something is wrong here, there is no anti-injection processing for sql
5, the first way to prevent injection (? method)
<?php try { $pdo=new PDO('mysql:host=localhost;dbname=php','root','root'); $sql="select * from user where name=? and pwd=?"; $stmt=$pdo->prepare($sql); $stmt->execute(array($username,$pwd)); echo $stmt->rowCount(); } catch (Exception $e) { echo $e->getMessage(); }
6, the second method (placeholder method)
<?php try { $pdo=new PDO('mysql:host=localhost;dbname=php','root','root'); $sql="select * from user where name=:name and pwd=:pwd"; $stmt=$pdo->prepare($sql); $stmt->execute(array(":name"=>$username,":pwd"=>$pwd)); echo $stmt->rowCount(); } catch (Exception $e) { echo $e->getMessage(); }
Enter 'or 1=1# in both ways and print both 0, solution Solved the sql injection problem.