简体   繁体   中英

PHP | PDO get all dynamic column name and Its value

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

在此处输入图片说明

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.

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM