php调用mysql存储过程游标

<?php
    $dbtype = 'mysql';
    $host = 'localhost';
    $dbname = 'test';
    $dsn = "$dbtype:host=$host;dbname=$dbname";
    $user = 'root';
    $password = 'root';
    try{
        $pdo = new PDO($dsn, $user, $password);
    } catch(PDOException $e) {
        echo $e->getMessage();
    }
    $procy = "
        create procedure proc1()--定义存储过程名字
        begin --开始
        declare mynum int default 0; --定义变量指定类型默认值
        declare done int default 0;
        declare cur1 cursor for select num1 from test.test1; --定义游标
        declare continue handler for not found  set done = 1; --定义游标内循环结束标志
        open cur1; --打开游标
        fetch cur1 into mynum; --打开游标并指向数据第一行
        while done != 1 do --while循环
            insert into test.test2(numc) value(mynum); --执行任意语句
            fetch cur1 into mynum; --指向下一条数据
        end while; --结束while
        close cur1; --关闭游标
        end;--结束存储过程
    ";
    $a = $pdo->query($procy);//存储编译存储过程(存储至mysql->proc表中)
    $res1 = $pdo->query('call proc1();');//调用存储过程
    $res2 = $pdo->query('select * from test2');
    var_dump($res2->fetchAll(PDO::FETCH_ASSOC));
    
    

 

posted @ 2016-11-24 15:30  不弃初衷  阅读(1600)  评论(0编辑  收藏  举报