使用execute数组与直接bind_param方法的优点

时间:2015-02-11 09:16:12

标签: php data-binding pdo

使用执行数组与直接bind_param方法的优点是什么,即

$stmtt = $conn->prepare($sql); 

$stmt->bindParam(':title', $_POST['title '], PDO::PARAM_STR); 
$stmt->execute();

1 个答案:

答案 0 :(得分:0)

我能想到两个优点。 (1)您可以使用bindParambindValue指定数据类型,而使用execute array会将所有内容视为字符串。在某些情况下,能够指定数据类型非常方便。例如:

 // Return the correct result
 $sh = $db->prepare("SELECT * FROM items LIMIT :offset,:length");
 $sh->bindValue(":offset", 0, PDO::PARAM_INT);
 $sh->bindValue(":length", 10, PDO::PARAM_INT);
 $sh->execute();

 // Does not return any result, unless you set PDO::ATTR_EMULATE_PREPARES to FALSE
 $sh = $db->prepare("SELECT * FROM items LIMIT :offset,:length");
 $sh->execute(array(
    "offset" => 0,
    "length" => 10
 ));

(2)如果要多次插入,bindParam可以更容易。例如:

$sh = $db->prepare("INSERT INTO news_tags(news_id, tag) VALUES(:id, :tag)");
$sh->bindValue(":id", 2);
$sh->bindParam(":tag", $tag);

foreach($tags as $value) {
    $tag = $value;
    $sh->execute();
}