如何计算MySQL表中的行数(PHP PDO)

时间:2017-06-30 07:37:53

标签: php mysql pdo

这是我的代码

$stmt = $conn->prepare("SELECT tmdb_movies.movie_title,tmdb_movies.tmdb_id, count (tmdb_id),GROUP_CONCAT(DISTINCT genres.genres_name) AS genres_name

FROM tmdb_movies

JOIN genres USING (tmdb_id)

GROUP BY tmdb_movies.movie_title,tmdb_movies.tmdb_id

HAVING find_in_set('$category1', genres_name) AND find_in_set('$category2', genres_name) 

LIMIT $limit OFFSET $start"); 


     // Then fire it up
     $stmt->execute();

 // Pick up the result as an array
 $result = $stmt->fetchAll();

由于我无法在同一代码中计算包含$category1$category2的总行数,因此我在此之前添加了此代码。

$sql = "SELECT count(tmdb_id),group_concat(genres.genres_name) AS genres_name

 FROM `tmdb_movies` 

JOIN genres USING (tmdb_id)
GROUP BY tmdb_movies.tmdb_id
HAVING find_in_set('$category1', genres_name) AND find_in_set('$category2', genres_name) "; 

$result = $conn->prepare($sql); 
$result->execute(); 
$totalrows = $result->rowCount();
echo $totalrows;

$totalrows在这里回复3。但是他们的行数要多于3个。

3 个答案:

答案 0 :(得分:1)

使用fetchAll()

执行后,您将覆盖$ stmt

所以请尝试这个

$stmt->execute();
 $totalrows = $stmt->rowCount(); 
 echo $totalrows;
 // Pick up the result as an array
 $result = $stmt->fetchAll();

答案 1 :(得分:0)

尝试使用rowCount()计算行数

$totalrows = $stmt->rowCount();

答案 2 :(得分:0)

试试这个

$stmt = $conn->prepare("SELECT SQL_CALC_FOUND_ROWS tmdb_movies.movie_title,tmdb_movies.tmdb_id, count (tmdb_id),GROUP_CONCAT(DISTINCT genres.genres_name) AS genres_name

FROM tmdb_movies

JOIN genres USING (tmdb_id)

GROUP BY tmdb_movies.movie_title,tmdb_movies.tmdb_id

HAVING find_in_set('$category1', genres_name) AND find_in_set('$category2', genres_name) 

LIMIT $limit OFFSET $start"); 


     // Then fire it up
     $stmt->execute();

 // Pick up the result as an array
 $result = $stmt->fetchAll();
 $conn->prepare('SELECT FOUND_ROWS() as COUNT');
 $conn->execute();
 $count = $conn->fetchColumn();
 echo $count; //here's your total count