douxun4924 2014-04-13 12:35
浏览 40
已采纳

列名和值获取PDO

I try to get the values for columns in a table. First i want to fetch the tables. then i did like:

$sql = $dbh->query("DESCRIBE `players` ;");
foreach ($sql->fetchAll(PDO::FETCH_NUM) as $k) {
    echo 'Table:'  . $k[0]. '<input type="text" values=""><br>  ' ;
}

So what is best way now to get value for each table in same foreach?

SOLUTION HOW I DID:

function getColumnValue($column,$name) {
        global $dbh;
        $sqll = ("SELECT `$column` FROM `players` WHERE `name`='$name' ");
        $sthh = $dbh->prepare($sqll);
        $sthh->execute();
        return $sthh->fetch(PDO::FETCH_ASSOC);
}


foreach ($sql->fetchAll(PDO::FETCH_NUM) as $k) {
    $test = getColumnValue($k[0],'Test');
    echo 'Table: '.$k[0] .' <input type="text" value="'.$test[$k[0]].'" style="color:#000;"> <br> ';
}
  • 写回答

1条回答 默认 最新

  • dongzhunnai0140 2014-04-13 14:21
    关注

    You have two options to do this:

    1. you use two separate queries as I explained in my comment to your question: one to fetch the table description as you already do and a second one to fetch the tables content (the rows). You need two (actually three) loops to iterate over the results, roughly like this:

      • fetch table description ("DESCRIBE TABLE tablename")
        • iterate over columns in result
        • output single column name
      • fetch contents of the table ("SELECT * FROM tablename ...")
        • iterate over rows inside the result
        • iterate over columns inside each row
          • output cell content of current row and column
    2. you can use a union query for this, though it's kind of ugly and does not really simplify the structure of your code:

      SELECT 'colname1' AS colname1, 'colname2' AS colname2, 'colname3' AS colname3 FROM table name

      UNION

      SELECT colname1, colname2, colname3 FROM table name

      This single query concatenates the results of the two contained separate subqueries, so it gives what you originally asked for. You just have to make sure you query the same number and type of columns in both subqueries. But be aware that this is not really good style, since it is hard to debug and hard to maintain.

    In general it is questionable if fetch the column names to output them is really such a good idea. I would think twice about this: you combine storage architecture and visualization into a single layer which is a bad idea: you will run into big problems when you have to make changes later on. Typically those different aspects should be kept separate for a good reason.

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

报告相同问题?

悬赏问题

  • ¥15 html5+css有人可以帮吗?
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?