简体   繁体   English

如何从PHP中的MySQL以表格式显示数据

[英]How display the data in table format from mysql in php

I am not able to get my head around it. 我无法解决这个问题。

I have this database table: 我有此数据库表:

category_id
category_name
steps_description

Now I want to show in format like this 现在我要以这种格式显示

Catgeory 1
Then all steps under it

Catgory2
then all steps under it

Can I do it with one mysql query? 我可以使用一个mysql查询吗?

Please show me how to loop through with PHP. 请告诉我如何遍历PHP。

EDIT: 编辑:
I have got the data in object format ie collection of objects 我有对象格式的数据,即对象的集合

I want the result like: 我想要这样的结果:

for all categories {

<table><tr><th>Catgory Name </th></tr>
<tr> <td>Step1 </td> </tr>
<tr> <td>Step2 </td> </tr>
<tr> <td>Step3 </td> </tr>
</table>
}

Something like that but with one query. 像这样,但有一个查询。

I'm not sure if I exactly know what you mean, but I will try anyway... . 我不确定我是否完全了解您的意思,但是我还是会尝试...。 I assume, you have many categoriy names within the table which aren't unique. 我假设您在表中有许多类别名称,这些名称不是唯一的。 And you have many steps for each of them. 每个步骤都有很多步骤。 Now you want to make a table for every category. 现在,您要为每个类别创建一个表格。 If this is right, you can try something like this: 如果这是正确的,则可以尝试如下操作:

    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    $stmt = $db->query("SELECT * FROM `table`");

    $arr_data = array();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $arr_data[$row['category_name']][] = $row['steps_description'];
    }
    foreach ($arr_data as $cat) {
        foreach ($cat as $step) {
            $str_steps .= '<tr><td>'.$step.'</td></tr>';
        }
        echo '<table>'.$str_steps.'</table>';
        $str_steps = '';
    }

Use PDO to connect and Fetch rows: 使用PDO连接并提取行:

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$stmt = $db->query("SELECT * FROM `table`");

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "<table><tr><td>".$row['category_name']." ".$row['category_id']."</td></tr>";
    echo "<tr><td>".$row['steps_description']."</td></tr></table>";
    echo "<br /><br />"
}

If you need to learn more about PDO, please read this nice tutorial 如果您需要了解有关PDO的更多信息,请阅读此教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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