所以我试图找回喜欢的列表。这是我的代码
//Echo total likes of #68
$stmt1 = $con->prepare("SELECT COUNT(*) FROM likes WHERE liked_post_id = :id;");
$stmt1->bindValue(':id', $id, PDO::PARAM_STR);
$stmt1->execute();
$count = $stmt1->rowCount();
echo $count;
我认为这会让所有人都喜欢。但我只得到1回归。这是结构
+-----------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| liked_post_id | varchar(255) | YES | | NULL | |
| liked_post_user | varchar(255) | YES | | NULL | |
| liked_post_ip | varchar(255) | YES | | NULL | |
+-----------------+------------------+------+-----+---------+----------------+
快速查询
+----+---------------+-----------------+---------------+
| id | liked_post_id | liked_post_user | liked_post_ip |
+----+---------------+-----------------+---------------+
| 77 | 68 | alex | 127.0.0.1 |
| 78 | 68 | andrew | 127.0.0.1 |
+----+---------------+-----------------+---------------+
因为我希望得到1
,而不是获得2
,因为有两个用户喜欢它。有任何想法吗?我也没有收到任何错误。
答案 0 :(得分:1)
这样做:
$stmt1 = $con->prepare("SELECT COUNT(*) AS count FROM likes WHERE liked_post_id = :id;");
$stmt1->bindValue(':id', $id, PDO::PARAM_STR);
$stmt1->execute();
$row = $stmt1->fetch(PDO::FETCH_ASSOC);
echo $row['count'];
查询返回1行,该行的内容是表中匹配行的计数。您需要获取行以读取该值。
答案 1 :(得分:0)
COUNT()是一个聚合函数,因此返回行数作为结果。如果您想获取列表,则应将COUNT(*)替换为*。
SELECT likes.* FROM likes WHERE liked_post_id = :id
答案 2 :(得分:0)
这是查询结果(SELECT COUNT(*) FROM likes WHERE liked_post_id = :id;
):
+----------+
| COUNT(*) |
+----------+
| 2 |
+----------+
rowCount();
返回返回的行数,SELECT COUNT(*) FROM likes WHERE liked_post_id = :id;
只返回1行,一行包含喜欢的行数。
您必须阅读该行的内容或以这种方式SELECT
完成SELECT * FROM likes WHERE liked_post_id = :id;
。后者的优化程度较低,但是如果要在代码的某些部分进行完整的选择,则可以重用返回的内容,这样就可以减少对数据库的查询。