Table from columns

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
vas2012
Forum Newbie
Posts: 2
Joined: Thu Mar 01, 2012 1:31 am

Table from columns

Post by vas2012 »

I’m working in php/mysql. I’m a starter and I have a problem.
I have connected with my database and I want to create a table from the database’s table:

The first one is a table in my database with all users’ data. (they are all numerical)

- - - - - - - - - - - - - - - - - - - - - -
| id | age | score | bonus |
- - - - - - - - - - - - - - - - - - - - - -
| 1 | 17 | 39 | 10 |
- - - - - - - - - - - - - - - - - - - - - -
| 2 | 12 | 31 | 10 |
- - - - - - - - - - - - - - - - - - - - - -
| 3 | 15 | 35 | 20 |
- - - - - - - -- - - - - - - - - - - - - - -
| 4 | 11 | 32 | 30 |
- - - - - - - - - - - - - - - - - - - - - - -
| 5 | 12 | 49 | 10 |
- - - - - - - - - - - - - - - - - - - - - - - -
etc…………………………………………………………

I want to create a table ‘Ages’ using the first two columns like that:
--- - - - - - - - - -
| id | age |
| 1 | 17 |
| 1 | 12 |
| 1 | 15 |
| 1 | 11 |
| 5 | 12 |
- - - - - - -- - - -

How could I do that?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Table from columns

Post by Celauran »

Code: Select all

<?php

$sql = new PDO('mysql:host=localhost;dbname=whatever', 'username', 'password');

$query = "SELECT id, name FROM table_name";
$result = $sql->query($query)->fetchAll(PDO::FETCH_OBJ);


?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <title>Debug</title>
    </head>
    <body>
        <table>
            <tr>
                <th>ID</th>
                <th>Age</th>
            </tr>
            <?php foreach ($result as $user): ?>
            <tr>
                <td><?php echo $user->id; ?></td>
                <td><?php echo $user->age; ?></td>
            </tr>
            <?php endforeach; ?>
        </table>
    </body>
</html>
vas2012
Forum Newbie
Posts: 2
Joined: Thu Mar 01, 2012 1:31 am

Re: Table from columns

Post by vas2012 »

Thank you. It was very helpful.
Post Reply