i have a query use PDO, count the row first, if row >1 than fetch data
SELECT * WHERE id=:id
$row=$SQL->rowCount();
if($row>0){
while($data=$SQL-&
As a matter of fact, neither PDO rowCount nor COUNT(*) is ever required here.
if row >1 then fetch data
is a faulty statement.
In a sanely designed web-application (I know it sounds like a joke for PHP) one don't have to make it this way.
Most sensible way would be
if needed, we can use this very fetched data to see whether anything was returned:
$data = $stmt->fetch();
if($data){
//use it whatever
} else {
echo "No record";
}
In your case, assuming id
is an unique index, only one row can be returned. Therefore, you don't need while
statement at all. Just use the snippet above either to fetch and to tell whether enythin has been fetched.
In case many rows are expected, then just change fetch()
to fetchAll()
and then use foreach to iterate the returned array:
$data = $stmt->fetchAll();
if($data){
foreach ($data as $row) {
//use it whatever
}
} else {
echo "No records";
}
Note that you should never select more rows than needed. Means your query on a regular web page should never return more rows than will be displayed.
Speaking of the question itself - it makes no sense. One cannot compare rowCount
VS COUNT(*)
, because it's incomparable matters. These two functions has absolutely different purpose and cannot be interchanged:
COUNT(*)
returns one single row with count, and have to be used ONLY if one need the count of records, but no records themselves.count(whatever)
is not faster nor slower - it's pointless.rowCount()
returns the number of already selected rows and therefore you scarcely need it, as it was shown above.Not to mention that the second example will fetch no rows at all.