Php PDO rowCount() return wrong result

Ann*_*na 0 php mysql pdo

I have a function for getting path in a tree structure data.

According to my table in DB, root should get no result when I query sub_id='root_id'

When I just pass the root the rowCount return correct result which is 0. However when I pass a node from lower rank(3rd), in the end of the recursive which is root, rowCount return 1?

PS

I use Mysql as DB

This is my table

main_id | sub_id
----------------    
    1   |    2    
    1   |    3    
    2   |    4    
    3   |    5
Run Code Online (Sandbox Code Playgroud)

The code:

$stmt = $conn->prepare("Select * from table where sub_id= ? ");  

function get_path($stmt,$node,&$map){

    $res=$stmt->execute(array($node));

    if(!$res){ throw new Exception( implode(' ',$stmt->errorInfo()),1); }

        echo $node.' found '.$stmt->rowCount().'<br>';

        if($stmt->rowCount()==0){ //root
            $map[]=$node;
        }else{

            foreach($stmt->fetchAll(PDO::FETCH_ASSOC) AS $row){
                $map[]=$node;
                $upper_node=$row['main_id'];
                get_path($stmt,$upper_node,$map);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

If I just pass get_path($stmt,1,$map); (the root)

the output:

1 found 0
Run Code Online (Sandbox Code Playgroud)

but when I for example pass 4 into it the output become:

4 found 1
2 found 1
1 found 1 <= it should found 0
Run Code Online (Sandbox Code Playgroud)

Why?

VMa*_*Mai 5

您不应该依赖 PDOStatement::rowCount() 来获取受 SELECT 语句影响的行数,请参阅PHP 手册, PDOStatement::rowCount

DOStatement::rowCount() 返回受相应 PDOStatement 对象执行的最后一个 DELETE、INSERT 或 UPDATE 语句影响的行数。

如果关联 PDOStatement 执行的最后一条 SQL 语句是 SELECT 语句,则某些数据库可能会返回该语句返回的行数。但是,这种行为并不能保证适用于所有数据库,并且不应依赖于可移植应用程序。

[...]

Example #2 统计 SELECT 语句返回的行数

对于大多数数据库,PDOStatement::rowCount() 不返回受 SELECT 语句影响的行数。相反,使用 PDO::query() 发出一个 SELECT COUNT(*) 语句,其谓词与您预期的 SELECT 语句相同,然后使用 PDOStatement::fetchColumn() 来检索将返回的行数。然后您的应用程序可以执行正确的操作。