在Php PDO中使用bindValue中的$id之前,我是否需要使用(int)$id


Do I need to use (int)$id before I use $id in bindValue in Php PDO

我刚刚开始使用Php数据对象,我不确定的一件事是,我必须验证一些变量是一个整数,然后在查询中使用它。例如,像这样:

$id = (int)$_POST['id']; // is this required    
$query = $pdo->prepare("SELECT * FROM `articles` WHERE `id` = ?");
$query->bindValue(1, $id);
$query->execute();

不需要,有两个原因:

  1. 你让PDO知道你要查询数据库的列ID。PDO不会解析$_POST['id']中的任何内容。

  2. bindValue的第二个值被自动转换为字符串(或您可能想要选择的任何类型)。这里int $data_type = PDO::PARAM_STR