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

时间:2017-04-19 08:00:04

标签: php mysql stored-procedures pdo

我有stored procedure。我通过PDO打电话。当我在Phpmyadmin中运行程序时。它返回如下的输出。

enter image description 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());

它返回

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

我如何获得列名?及其价值。谢谢。

1 个答案:

答案 0 :(得分:1)

假设:

$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());

...将生成:

$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?'=>''
        ]
    ]
];

...你可以用这个构建一个简单的表:(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>";

输出:

<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>

像这样渲染:

enter image description here