如何使用PHP从下面的查询MySQL查询中获取计数值。
这是我的MySQL代码。
$dbc = mysqli_query($mysqli,"SELECT COUNT(*) FROM((SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1')
UNION
(SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.friend_id = users.user_id
WHERE users_friends.friend_id = 1
AND users_friends.friendship_status = '1')) as friends");
答案 0 :(得分:1)
使用SQL_CALC_FOUND_ROWS应该简化:
$dbc = mysqli_query($mysqli,"SELECT SQL_CALC_FOUND_ROWS users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1'
");
然后再做
$rs = mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$rec = $rs->fetch_array();
$count = $rec[0];
此方法将返回与查询匹配的记录数,忽略任何LIMIT语句,而使用$rs->num_rows
将仅提供实际返回的记录数。取决于你想要的那个。
答案 1 :(得分:0)
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
答案 2 :(得分:0)
假设您已正确连接到MySQL服务器并且查询正确执行,您可以使用以下代码:
$values = mysql_fetch_row($dbc);
$count = $values[0];
答案 3 :(得分:0)
您的查询看起来应该像SELECT numThings
FROM xxx
您将在PHP中引用numThings:
$result = mysql_query("SELECT COUNT(*) as `numThings` FROM xxx");
$row = mysql_fetch_assoc($result);
$count = $row['numThings'];