Php 应该使用哪种PDO绑定方法来提高安全性?
我知道在PHP中使用PDO更新MySQL数据库记录的两种方法。请有人解释一下,为了更好的安全性,我应该使用哪一种,以及它们之间的区别,我有点困惑 方法一:Php 应该使用哪种PDO绑定方法来提高安全性?,php,mysql,security,pdo,sql-injection,Php,Mysql,Security,Pdo,Sql Injection,我知道在PHP中使用PDO更新MySQL数据库记录的两种方法。请有人解释一下,为了更好的安全性,我应该使用哪一种,以及它们之间的区别,我有点困惑 方法一: $user = "root"; $pass = ""; $dbh = new PDO('mysql:host=somehost;dbname=somedb', $user, $pass); $sql = "UPDATE coupons SET coupon_code = :coupon_code, valid_from = :valid_
$user = "root";
$pass = "";
$dbh = new PDO('mysql:host=somehost;dbname=somedb', $user, $pass);
$sql = "UPDATE coupons SET
coupon_code = :coupon_code,
valid_from = :valid_from,
valid_to = :valid_to,
discount_percentage = :discount_percentage,
discount_amount = :discount_amount,
calculationType = :calculationType,
limit = :limit
WHERE coupon_code = :coupon";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':coupon_code', $_POST['coupon_code'], PDO::PARAM_STR);
$stmt->bindParam(':valid_from', $_POST['$valid_from'], PDO::PARAM_STR);
$stmt->bindParam(':valid_to', $_POST['valid_to'], PDO::PARAM_STR);
$stmt->bindParam(':discount_percentage', $_POST['discount_percentage'], PDO::PARAM_STR);
$stmt->bindParam(':discount_amount', $_POST['discount_amount'], PDO::PARAM_STR);
$stmt->bindParam(':calculationType', $_POST['calculationType'], PDO::PARAM_STR);
$stmt->bindParam(':limit', $_POST['limit'], PDO::PARAM_STR);
$stmt->bindParam(':coupon', $_POST['coupon_code'], PDO::PARAM_STR);
$stmt->execute();
方法二:
$dbtype="somedbtype";
$dbhost="somehost";
$dbname="somedb";
$dbuser="someuser";
$dbpass= "somepass";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$title = 'PHP Pattern';
$author = 'Imanda';
$id = 3;
$sql = "UPDATE books
SET title=?, author=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($title,$author,$id));
据我所见,方法2不绑定数据,而是将其作为数组类型直接插入查询中。这是否会使脚本更容易受到SQL注入或其他安全风险的影响?两者之间的唯一区别是,如果您将数组传递给
execute
函数,而不是自己调用bindParam
,它会自动将所有参数视为PDO::PARAM_STR
,而在自己调用bindParam
时,可以将它们绑定为整数等
从:
输入参数
包含与正在执行的SQL语句中的绑定参数数量相同的元素的值数组。所有值都被视为PDO::PARAM_STR
从示例中还可以看出,在将数组传递到execute
函数时,可以使用命名参数(例如:limit
)。你不必把?
放进去。在这种情况下,为数组指定一个键:
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
这主要是偏好的问题。两者都能防止注射
虽然我认为使用bind()强制数据类型要容易得多,但是使用execute(array())将使用字符串。非常有用,谢谢!我正在将我所有的mysqli更新为PDO以进行内务管理,我想知道其中的区别。谢谢:D