准备好的陈述-是否必要 [英] prepared statements - are they necessary

查看:75
本文介绍了准备好的陈述-是否必要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

准备好的陈述会添加大量代码...但是我一直听到有人提到要使用它们...从1行代码增加到大约6行会增加什么价值?这仅仅是为了防止SQL注入吗?

类似的帖子此处. /p>

有关准备好的语句的php.net 此处

解决方案

准备好的语句为防止SQL注入提供了出色的保护.

除了SQL注入保护外,当多次执行同一查询时(例如在INSERT循环中),准备好的语句还减少了数据库服务器上的负载.该语句仅由RDBMS编译一次,而不必像在mysql_query()调用中那样每次都编译.

不同的API需要不同数量的代码才能执行准备好的语句.我发现,例如,如果您的情况允许PDO在execute()调用中使用隐式参数绑定,则PDO可能比MySQLi更为冗长.仅当您所有的参数都可以评估为字符串时,此方法才有效.

// PDO implicit binding example:
// Not many lines of code if the situation allows for it
$stmt = $pdo->prepare("SELECT * FROM tbl WHERE col1=? AND col2=? AND col3=?");
$stmt->execute(array($val1, $val2, $val3));

Prepared statments add a significant amount of code...yet I keep hearing mentions to use them...what value is added by going from 1 line of code to about 6? Is this simply to protect against sql injection?

Similar post here.

php.net on prepared statements here

解决方案

Prepared statements offer excellent protection against SQL injection.

In addition to SQL injection protection, prepared statements offer reduced load on the database server when the same query is to executed multiple times, such as in an INSERT loop. The statement is only compiled once by the RDBMS rather than needing to be compiled each time as it would in a mysql_query() call.

Different APIs require varying amounts of code to execute a prepared statement. I find that PDO can be a little less verbose than MySQLi, if for example your situation permits the use of implicit parameter binding inside the execute() call. This only works, if all your params can be evaluated as strings though.

// PDO implicit binding example:
// Not many lines of code if the situation allows for it
$stmt = $pdo->prepare("SELECT * FROM tbl WHERE col1=? AND col2=? AND col3=?");
$stmt->execute(array($val1, $val2, $val3));

这篇关于准备好的陈述-是否必要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆