duanpacan9388 2014-07-29 15:19
浏览 90
已采纳

Php pdo:是否可以在递归中重用prepare语句

trying to go through a tree structure data in DB

the table is kinda like this

main_id  sub_id
------------------------
1            2
1            3
2            4
3            5

my function is below:

$sql="Select * from info_map where main_id= ? ";
$stmt=$conn->prepare($sql);
if(!$stmt){ throw new Exception ( implode(' ',$conn->errorInfo()),0); }

search_child($stmt,215);

function search_child($stmt,$mom){   

   $res=$stmt->execute(array($mom));
   if(!$res){ throw new Exception( implode(' ',$stmt->errorInfo()),1); }
   $rc=$stmt->rowCount();

   if($rc>0){
        while($row = $stmt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)){
            $nextMom=$row['sub_id'];
            echo $mom.'->'.$nextMom.'<br>';
            search_child($stmt,$nextMom);

        }    
}

The $stmt=$conn->prepare() was inside the function and I got the result I want (return all the children and their grandchildren....etc)

but it is not reusing the prepare statement since we run the same sql.

So I move the $stmt=$conn->prepare() out of function like the code above, but in this way it only return one child and its grandchild.

Can I reuse statement object like this in recursive function? or I just did something wrong?


Update: @Barmar your reply help me realize why I got only one line of family tree, because when the loop go back to 2nd child of 2nd generation the statement obj has been gone since it has been used to other generation's query (descendants of the 1st child of the 2nd generation ) thank you.

  • 写回答

1条回答 默认 最新

  • duandong1869 2014-07-29 18:12
    关注

    As hinted by @Barmar, there may be some conflicting between php and the mysql server. I usually pass prepared statements for my recursive functions without problem, but get the results through a fetchAll() like this:

    function search_child($stmt,$mom){   
    
        $res=$stmt->execute(array($mom));
        if(!$res){ throw new Exception( implode(' ',$stmt->errorInfo()),1); }
    
        foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row){ 
        // PDO fetch orientation is next by default. no need to specify it.
            $nextMom=$row['sub_id'];
            echo $mom.'->'.$nextMom.'<br>';
           search_child($stmt,$nextMom);
        }   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案