Populate Table with PHP

Hello!

In a vain attempt to procrastinate from mountains of coursework I have decided to write a wee tutorial using php and mysqli.

1. Database

First build a database similar to the layout below.

local2

2.HTML/PHP/CSS

[code language="php"]
<style>
table {
 font-family: arial, sans-serif;
 border-collapse: collapse;
 width: 100%;
}

td, th {
 border: 1px solid #dddddd;
 text-align: left;
 padding: 8px;
}

tr:nth-child(even) {
 background-color: #dddddd;
}
</style>
<?php 
// make connection
$con=mysqli_connect('localhost','root','password','addressbook');


if (!$con) {
 die ( "failed to connect: " .mysqli_connect_error());
}

$sql = "SELECT ID, Name, phoneNumber, Organisation FROM employee";
// query made
$result = mysqli_query($con, $sql);

// Setup table and populate with database values 

?>
<table>
 <tr>
 <th>Id</th>
 <th>Name</th>
 <th>Number</th>
 <th>Company</th>
 </tr>

 <?php
if (mysqli_num_rows($result) > 0) {
 // output data of each row
 while($row = mysqli_fetch_assoc($result)) {
 echo "<tr><td>" . $row["ID"] . "</td>" . " " . "<td>" . $row["Name"]. "</td>" ." " . "<td>" . $row["phoneNumber"] . " </td>" . "<td>" . " " . $row["Organisation"] . "</td></tr>" ."<br>";
 }
echo "</table>";
} else {
 echo "0 results";
}

?>
<br>
<a href="index.php">back</a>


[/code]

 

Okay so this firstly asks for a connection to the database with an error handler if the connection is not made. Next comes the query with the appropriate fields selected. Next the query is parsed with the connection for later on. After this the top of the tables including the table headings are readied. This is the slightly tricky part, so the query is fetched as normal but this time as the values are echoed a table dimension tag is opened and closed as each value is outputted. after the table row is closed, the last table tag is shut.

At the start there are some styling for the table to make it slightly more pretty.

3. That’s it! Wait… What??

Yep that’s it! a few quirks but I’m sure you will get there 🙂

Thanks folks hoped this helped some of you guys!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s