public function checkForeignKey($aId) {
$statement = $this->connection->prepare("SELECT COUNT(*) FROM cursusleerling WHERE cursusid = ?");
$statement->bindValue(1, $aId);
$statement->execute();
return $statement->fetchColumn() > 0;
}
这可以返回true或false,但是如何检查该值?
答案 0 :(得分:1)
做
return $statement->fetchColumn() > 0;
将计算表达式,检查是大于零的列,因此返回布尔值true
/ false
;如果计数大于零,则true
,否则为false
。
如果您只是返回$statement->fetchColumn()
而不检查> 0
,则会得到确切的倒数而不是布尔值。由于PHP是弱/松散类型的,1 == true
等表达式为真*,你也可以在if语句中使用结果,就像这样
public function checkForeignKey($aId) {
$statement = $this->connection->prepare("SELECT COUNT(*) FROM cursusleerling WHERE cursusid = ?");
$statement->bindValue(1, $aId);
$statement->execute();
return $statement->fetchColumn(); // removed > 0
}
/* Class defined and such above, using it below */
$obj = new YourClass(..); /* We only see a method of your class, not the whole thing, so just using some psudocode */
$count_result = $obj->checkForeignKey(1337);
if ($count_result) {
echo "The result was ".$count_result;
} else {
echo "No results returned";
}
*在强类型语言中,1 == true
为false。您可以进行严格的比较1 === true
(三个等式),这在PHP中是错误的
答案 1 :(得分:0)
return $statement->fetchColumn() > 0;
此行检查列数,因此返回true或false。
return $statement->fetchColumn();
返回列数