Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Pontus Bolmér
Pontus Bolmér
12,471 Points

Writing all the info out from mysql

This might be so easy it's stupid

But let say i make a query from my database with mysql. And i just want to list out all the information up and down from the query.

So lets say i have a database with 5 columns, with forname, lastname, age, personalnumber, adress. So if i would like to write out all the fornames, i would simply type $row["forname"]

So what i want is, to simply type $row and display all it's contents. And not $row["forname"] $row["lastname"] and so on.

2 Answers

Niki Molnar
Niki Molnar
25,575 Points

Hi Pontus

I didn't discover this until I'd been using PHP and MySQL for 5 years - but it's a huge time saver!

Without any data validation from the server, this is what it would look like as a table:

$sql = "SELECT forname, lastname, age, personalnumber, adress FROM users";
$result = mysqli_query($db, $sql);
echo "
<table>
    <thead>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Age</th>
        <th>Phone</th>
        <th>Address</th>
    </tr>
    </thead>
    <tbody>";
while($row = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    foreach($row as $item) {
        echo "<td>" . $item . "</td>";
    }
    echo "<tr>";
}
echo "
    </tbody>
</table>";

Hope that helps!

Niki

Pontus Bolmér
Pontus Bolmér
12,471 Points

Hey! Thanks for the amazing answer Niki! This really helps me out!

Yours / Pontus