我有一个画廊的 SQL 表,其中包含 id、userid、imagename 行。 我正在尝试编写一个函数来计算某个用户添加了多少图像,我是 PDO 和 SQL 的新手。这就是我的职能;
// Photo Count
public function photoCount($id){
$this->db->query('SELECT * FROM gallery WHERE id = :id');
// Bind value
$this->db->bind(':id', $id);
$row = $this->db->single();
// Check row
$count = $this->db->rowCount();
return $count;
}
我是否需要行 $row = $this->db->single();
或者我可以在返回所有内容时只返回 rowCount
是 0,这是不正确的。
任何帮助表示赞赏。
最佳答案
使用SQL计数功能。如果 $this->db
是 PDO 对象,那么...
public function photoCount($id){
$statement = $this->db->prepare('SELECT count(*) as c FROM gallery WHERE id = :id');
$statement->bindParam(":id", $id);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_OBJ);
return $result->c;
}
关于php - 使用 PDO 查询的 SQL 表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53530495/