mysqli-预处理防止SQL注入

如果不防止SQL注入,则利用' or 1=1 #就可以实现登录操作
如图所示,#代表注释
截图未命名.jpg

<?php
header('content-type:text/html;charset=utf8;');
$mysqli = new mysqli('localhost','root','root','muke');
if($mysqli->connect_errno){
    die('Connect Error'.$mysqli->connect_error);
}
$mysqli->set_charset('utf8');
$username=$_POST['username'];
$password=md5($_POST['password']);
//$sql = "SELECT * FROM user WHERE username='{$username}' AND password='{$password}'";
//$mysqli_result=$mysqli->query($sql);
//if($mysqli_result && $mysqli_result->num_rows>0){
//    echo '登录成功';
//    echo '<br>'.$sql;
//}else{
//    echo '登录失败';
//}
$sql="SELECT * FROM user WHERE username=? AND password=?";
$mysqli_stmt=$mysqli->prepare($sql);
$mysqli_stmt->bind_param('ss',$username,$password);
if($mysqli_stmt->execute()){
    $mysqli_stmt->store_result();
    if($mysqli_stmt->num_rows>0){
        echo '登录成功';
        echo $sql;
    }else{
        echo '登录失败';
    }
}
//释放结果集
$mysqli_stmt->free_result();
//关闭预处理语句
$mysqli_stmt->close();
//关闭数据库连接
$mysqli->close();

发表评论