0

I have a SELECT query, like this:

$stmnt = $conn->prepare("SELECT post_title, posts_cat FROM posts WHERE posts_cat=:posts_cat");
$stmnt->execute(array(':posts_cat' => $cat_id));
$post_info = $stmnt->fetch();
$count = $stmnt->rowCount();

If there are no posts it shows none, but if there's one or more then it displays only one.

Can someone tell me why this is?

krlzlx
  • 5,752
  • 14
  • 47
  • 55
Jordyn
  • 1,133
  • 2
  • 13
  • 28

3 Answers3

2

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

rowCount() is not for a SELECT query, use a separate COUNT query for that or fetch all rows in an array and count its size

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
1

Please do not use rowCount() with select query
use a different query with count() for counting rows

$sql = "SELECT count(*) FROM `posts` WHERE posts_cat = :posts_cat"; 
$stmnt = $conn->prepare($sql); 
$stmnt->execute(array(':posts_cat' => $cat_id)); 
$count = $stmnt->fetchColumn(); 
Rajesh Patel
  • 1,946
  • 16
  • 20
0

Of course you are getting the right number of rows returned. 1 means that only one row was found. If you want more rows to be found, add more rows to your database to match the condition.

Whether you need such a function at all - is another question, already answered in this post

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345