dongzhanyan3667 2017-04-19 08:00
浏览 30

PHP | PDO获取所有动态列名称及其值

I have a stored procedure. I'm calling through PDO. when I run the procedure in Phpmyadmin. It return output like below.

enter image description here

Problem

I don't know how many columns will stored procedure returns. I need column name and its Value name.

My Attempt here

$sql = "call surveyreport (28);";   
$stmt = $pdo->query($sql);
$a=array();
do {
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rows) {
    array_push($a, $rows);
}
} while ($stmt->nextRowset());

it returns

Array ( [0] => Array ( [0] => Array ( [0] => 1068 [1] => SATHIYA MOORTHI [2] => Yes [3] => ) [1] => Array ( [0] => 5000 [1] => Ben Praveen [2] => Yes [3] => ) ) )

How Can I get Column name? and Its value. Thank You.

  • 写回答

1条回答 默认 最新

  • duanfei1987 2018-02-15 11:44
    关注

    Assuming:

    $sql = "CALL surveyreport (28);";   
    $stmt = $pdo->query($sql);
    $survery=array();
    do {
        if($rows = $stmt->fetchAll(PDO::FETCH_ASSOC)){
            array_push($a, $rows);
        }
    } while ($stmt->nextRowset());
    

    ...will generate:

    $a=[
        [
            [
             'EmpId'=>1068,
             'Name'=>'SATHIYA MOORTHI',
             'Is thisuseful ?'=>'Yes',
             'what did you learn from this?'=>''
            ]
        ],
        [
            [
             'EmpId'=>5000,
             'Name'=>'Ben Praveen',
             'Is thisuseful ?'=>'Yes',
             'what did you learn from this?'=>''
            ]
        ]
    ];
    

    ...you can build a simple table with this: (Demo)

    echo "<table border=\"1\" cellpadding=\"4px\" style=\"white-space:nowrap;\">";
        echo "<tr><th>",implode('</th><th>',array_keys(current(current($a)))),"</th></tr>";
        foreach($a as $surveyreports){
            foreach($surveyreports as $rows){
                echo "<tr><td>",implode('</td><td>',$rows),"</td></tr>";
            }
        }
    echo "<table>";
    

    Outputting this:

    <table border="1" cellpadding="4px" style="white-space:nowrap;">
        <tr>
            <th>EmpId</th><th>Name</th><th>Is thisuseful ?</th><th>what did you learn from this?</th>
        </tr>
        <tr>
            <td>1068</td><td>SATHIYA MOORTHI</td><td>Yes</td><td></td>
        </tr>
        <tr>
            <td>5000</td><td>Ben Praveen</td><td>Yes</td><td></td>
        </tr>
    <table>
    

    Rendering like this:

    enter image description here

    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应