【问题标题】:PHP | PDO get all dynamic column name and Its valuePHP | PDO 获取所有动态列名及其值
【发布时间】:2017-09-15 08:03:42
【问题描述】:

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

问题

我不知道存储过程会返回多少列。我需要列名及其值名称。

我的尝试

$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] => ) ) )

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

【问题讨论】:

  • 如果您获取关联而不是数字,您会将索引作为列名。我还想说,将列名设置为Is thisuseful ? 可能会引起更多的头痛而不是好处。 usefulness 可能是一个更好的名称(没有任何长名称,或者其中包含空格和符号)
  • PDO::FETCH_NUM => PDO::FETCH_ASSOC。列名应该简化,就像我说的,阅读stackoverflow.com/questions/7899200/…
  • @Qirel,谢谢。我得到了包含所有列名和值的数组。如何从该数组中拆分数据。数组如下所示Array ( [0] => Array ( [0] => Array ( [EmpId] => 1068 [Name] => SATHIYA MOORTHI [Is thisuseful ?] => Yes [what did you learn from this?] => ) [1] => Array ( [EmpId] => 5000 [Name] => Ben Praveen [Is thisuseful ?] => Yes [what did you learn from this?] => ) ) )
  • 取决于你想用它做什么以及你需要如何构建它。也许通过使用extract()?但这确实是另一个问题。
  • @Qirel,谢谢。对。我得到了当前问题的答案。

标签: php mysql stored-procedures pdo


【解决方案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>

像这样渲染:

【讨论】:

    猜你喜欢
    • 2017-12-23
    • 1970-01-01
    • 2011-10-04
    • 2014-05-27
    • 2011-07-22
    • 1970-01-01
    • 2020-05-27
    • 2010-12-21
    相关资源
    最近更新 更多