PDO - Which is better: columnCount or rowCount?

Asked

Viewed 892 times

1

I’m new to PDO (I was forced to choose between mysqli and Pdo after migrating php from version 5.2 to 7.0) and made a system where the user does the search:

$b2 = $_POST['b2'];
$busca = $PDO->query("SELECT * FROM noticias WHERE titulo LIKE '%$b2%' UNION SELECT * FROM noticias WHERE corpo LIKE '%$b2%'");

$total->columnCount();

OR

$total->rowCount();

At the end will be used to display the following information:

A busca retornou <?php echo $total ?> resultados;

2 answers

1

It’s not a question of "which is best", it’s functions with different purposes.

According to PDO documentation:

columnCount - Returns the number of columns obtained in the query result

and

rowCount - Returns the number of rows affected by the SQL statement

rowCount will only return something if you do DELETE, INSERT or UPDATE. Some databases may return the registration number if you only make a SELECT, but it is not guaranteed.

Like fetchAll returns an array, you can simply use count to check the number of results

count($busca->fetchAll())
  • When I said "which is the best" I meant which is the most recommended/performatic/fast for this situation, but I will test with fetchAll too, thank you for the answer.

  • if you want to count the lines, columnCount is not an option, therefore, you have only rowCount or make a count in the result array.

  • Funny @juniorgarcia here both (columnCount, rowCount and Count($search->fetchAll()) returned the same result and worked, for now I’m choosing columnCount, I read in php.net documentation that fetchAll searches ALL line results, then I imagine to be the heaviest to pick up and show the pagination, correct me if I’m wrong...

  • fetchAll will return all lines that fall into your SELECT. Since you want paging, you can only use fetch and rotate within a loop to control it. So you don’t need to pick up all the lines. And columnCount is to count columns, not results. Remember this :)

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.