php pdo - 检索结果和行数 - 便携式解决方案

I'm currently querying the db twice to retrieve the row count of my result set, and my result set before I run loops on the rows returned like this:

$result = $db->query("SELECT COUNT(*) FROM mytable");
$result1 = $db->query("SELECT * FROM mytable");

$count = $result->fetchColumn();

if($count == $value){

while($row = $result1->fetch(PDO::FETCH_ASSOC)){
//execute code
    }
} elseif($count == $value2) { 
//execute other code 
}

I've just converted to PDO and so don't know it as well. The code used to use mysql_num_rows. I'm looking for a way I can do this without querying the db twice, this solution that I've been using works for small purposes but is obviously unnecessary load on the database if it were scaled. Many Thanks

EDIT: My reason for moving to PDO is for it's portability features, and thus rowCount() isn't suitable in every instance.

You can use rowCount() method to get number of rows, like this:

$result = $db->query("SELECT * FROM mytable");
$count = $result->rowCount();

echo $count;

while($row = $result->fetch(PDO::FETCH_ASSOC)){

    // your code

}

Here's the reference:

Edited:

In case you don't want to use rowCount() method, this is another way of doing it.

$result = $db->query("SELECT * FROM mytable");
$result_set = $result->fetchAll();
$count = count($result_set);

echo $count;

while($row = array_shift($result_set)){

    // your code

}

Here are the relevant references:

In your case, there's no reason to perform a COUNT(*) query. You can just count how many rows were returned.

$count = $result->fetchAll();

Now $count holds reference to how many rows were returned.