dongtang8678 2015-03-31 20:51
浏览 41
已采纳

函数PDO查询和多维数组

I'm trying to get a multidimensional array returned from a function.

I want to have the column names as first level and data as second level.

array[columnName][data]

I can var_dump() the function and get the correct output, but I can't echo() the output.

<?php

function fetch_columname($schema,$tablename)
{
    try
    {
        $dbh = new PDO("mysql:host=host;dbname='dbname', 'user', 'pass'");
        $query = $dbh->prepare("SELECT `COLUMN_NAME` FROM    `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`=:schema AND `TABLE_NAME`=:tablename");
        $query->bindParam(":schema", $schema);
        $query->bindParam(":tablename", $tablename);
        $query->execute();

        $result = array();
        while($row = $query->fetch(PDO::FETCH_ASSOC))
        {
            $result[] = $row;
        }
        $dbh = null;
    }
    catch (PDOException $e)
    {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
    return $result;
}
$columname = array();
$columname = fetch_columname('new_site','users');
$count = count($columname);

for($i=0;$i<$count;$i++)
{
    echo $columname[$i];
}
  • 写回答

1条回答 默认 最新

  • dongqiang4819 2015-04-01 15:51
    关注

    From Mike's comment:

    Your function would return a two-dimensional array as written, though I am honestly not sure why you want a two-dimensional array considering you are only returning a single field in your query. I would simply change $result[] = $row to $result[] = $row['COLUMN_NAME'] and call it a day.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器