简体   繁体   中英

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?

Please show me how to loop through with 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:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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