下面的代码可以有效防止 sql 注入吗 ?

WBOY
Release: 2016-06-06 20:35:22
Original
997 people have browsed it

下面的代码可以有效防止 sql 注入吗 ?

大家一般是怎么做的 .

<code><?php $dbh = new PDO("mysql:host=localhost; dbname=mydb", "root", "pass");

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //禁用prepared statements的仿真效果
$dbh->exec("set names 'utf8'"); 

$sql="select * from table where username = ? and password = ?";

$query = $dbh->prepare($sql); 

$exeres = $query->execute(array($username, $pass)); 

if ($exeres) { 

    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
    }
    
}
$dbh = null;

?>
</code>
Copy after login
Copy after login

回复内容:

下面的代码可以有效防止 sql 注入吗 ?

大家一般是怎么做的 .

<code><?php $dbh = new PDO("mysql:host=localhost; dbname=mydb", "root", "pass");

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //禁用prepared statements的仿真效果
$dbh->exec("set names 'utf8'"); 

$sql="select * from table where username = ? and password = ?";

$query = $dbh->prepare($sql); 

$exeres = $query->execute(array($username, $pass)); 

if ($exeres) { 

    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
    }
    
}
$dbh = null;

?>
</code>
Copy after login
Copy after login

建议这样写, 能更有效的防注入

<code>......

$sql="select * from table where username = ?";

......


    while ($row = $query->fetch(PDO::FETCH_ASSOC) && $row['pass'] == $pass) {
        print_r($row);
    }
</code>
Copy after login

你的代码完全可以防止SQL注入,因为PDO就是SQL预处理的。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template