【问题标题】:Formatting results of fetchAll()fetchAll() 的格式化结果
【发布时间】:2023-03-28 05:01:01
【问题描述】:

我在 sql 语句上使用 fetchAll(PDO::FETCH_ASSOC) 来查询我创建的数据库,目前使用 print_r() 作为查看它的一种方式。 print_r 返回值如

Array ( [0] => Array ( [Type] => Poison, Invicibility, Heals [First_Name] => Acton [Last_Name] => Mooney ) 
        [1] => Array ( [Type] => Telepathy, Mind-Control [First_Name] => Adam [Last_Name] => Warlock ) 

我正在尝试使用循环将此信息放入表格中以使其样式美观整洁,例如我想看看:

         Type                          First_Name    Last_Name
Poison, Invicibility, Heals              Acton         Mooney
Telepathy, Mind-Control                  Adam          Warlock

但是我目前对如何实现这一点感到困惑。我知道它涉及某种类型的循环,但查询是动态的,有时可能有超过 3 行的信息,所以有点混乱。

【问题讨论】:

    标签: php pdo


    【解决方案1】:

    读取结果时使用while循环,不使用fetchAll();

    $stmnt = $db->prepare($sql);
    $stmnt->execute($aParams);
    while($row = $stmnt->fetch()) {
        echo stuff here....
    }
    $stmnt = null;
    

    编辑:基于对问题的澄清“我的问题是我如何知道列号和名称,因为我的查询的工作方式是它可以查询任何表”

    // Use fetchAll as you have
    $aResults = $stmnt->fetchAll(PDO::FETCH_ASSOC)
    
    // Then, check you have results
    $numResults = count($aResults);
    if (count($numResults) > 0) {
        // Output the table header
        echo '<table><tr>';
        foreach ($aResults[0] as $fieldName=>$value) {
            echo '<th>' . htmlspecialchars($fieldName) . '</th>';
        }
        echo '</tr>';
    
        // Now output all the results
        foreach($aResults as $row) {
            echo '<tr>';
            foreach ($row as $fieldName=>$value) {
                echo '<td>' . htmlspecialchars($value) . '</td>';
            }
            echo '</tr>';
        }
    
        // Close the table
        echo '</table>';
    } else {
        echo 'No results';
    }
    

    【讨论】:

    • 我的问题是我如何知道列号和名称,因为我的查询工作方式是它可以查询任何表。有没有办法指示循环解析这些信息?
    • 不客气。下次更清楚的问题;)
    【解决方案2】:

    像这样,

    <?php 
    
    $arr = array ( 0 => array ( 'Type' => 'Poison, Invicibility, Heals', 'First_Name' => 'Acton', 'Last_Name' => 'Mooney' ) ,
            1 => array ( 'Type' => 'Telepathy, Mind-Control', 'First_Name' => 'Adam', 'Last_Name' => 'Warlock' )) ;
    
    echo "<table><tr><th>type</th><th>type</th><th>type</th></tr>";
    
    foreach ($arr as $key=>$val) {
        echo "<tr>";
        echo "<td>".$val['Type']."</td>";
        echo "<td>".$val['First_Name']."</td>";
        echo "<td>".$val['Last_Name']."</td>";
        echo "</tr>";
    }        
    echo "</table>";      
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多