Creating a table in PHP involves generating HTML elements such as <table>, <thead>, <tbody> and <tr> from server-side data. PHP loops can create rows dynamically, while CSS helps tables remain usable on small screens. Always escape untrusted output so that special characters are displayed as text rather than interpreted as HTML.
This guide covers static and dynamic tables, safe output handling and accessibility considerations. Understanding open source software and database queries can provide useful background for more advanced examples.
What is PHP?
PHP is processed on the server before the page is sent to the browser. Therefore, tables can be built from arrays or databases, without having to manually write each row. If using a local environment like XAMPP, check the system versions that are still supported and the documentation Official PHP; old tutorials may contain historical installation steps.
PHP is a programming language widely used in website development and creation. This language has advantages that make it popular among web developers, such as the ability to interact with databases and generate dynamic content. PHP stands for “PHP: Hypertext Preprocessor” and was developed in 1994 by Rasmus Lerdorf. PHP was originally known as “Personal Home Page Tools” because it was initially used to build personal websites. However, with rapid development, PHP has evolved into a powerful web and database programming language.
Basic PHP Syntax
Before learning how to create tables in PHP, it’s important to understand basic PHP syntax. Every programming language has different writing rules, and PHP is no different. Here are some basic syntaxes you should know:
PHP code begins with the tag All PHP code must be placed between these two tags. For example:
<?php
echo "Halo, dunia!";
?>
The echo command is used to display text or variable values. For example:
<?php
$nama = "John Doe";
echo "Halo, " . $nama;
?>
Variables begin with a dollar sign ($). Variables can be used to store values and are used in PHP code. For example:
<?php
$umur = 25;
echo "Umur saya " . $umur . " tahun";
?>
Comments can be used to provide explanations or notes within PHP code. Comments are not executed by the PHP interpreter. There are two types of comments in PHP: single-line comments using // and multi-line comments using /* and */. For example:
<?php
// Ini adalah komentar satu baris
/*
Ini adalah komentar
multi-baris
*/
echo "Halo, dunia!";
?>
10 HTML Elements in Creating Tables
Use <th scope="col"> for column headers and <caption> If the information requires a title, data tables should not be used for page layout. If the application has a menu, study it. navigation bar as a different navigation component. Table design also needs to consider website user needs and phone screen.
To create a table in HTML, there are several elements you need to know. Here are 10 HTML elements used in creating tables:
1. <table>
The <table> element is used as the main container for tables in HTML. This element marks the start and end of a table.
2. <thead>
The <thead> element is used to store the table header row. This element marks the section containing information about the table’s columns.
3. <tbody>
The <tbody> element is used to store rows of data in a table. This element marks the section containing the table information.
4. <tr>
The <tr> element is used to store rows in a table. This element identifies each row in the table, which consists of one or more cells.
5. <th>
The <th> element is used to store table header cells. This element marks cells that contain information about the columns in the table.
6. <td>
The <td> element is used to store data cells in a table. This element marks cells that contain information or values in the table.
7. <caption>
The <caption> element is used to add a title or caption to a table. This element provides a brief description of the table being displayed.
8. <col>
The <col> element is used to specify the same column attributes for all columns in a table. This is useful when you want to set the same style or properties for multiple columns in a table.
9. <colgroup>
The <colgroup> element is used to specify the same column attribute for multiple columns in a table. You can specify the number of columns to which the attribute applies by adding the “span” attribute to the <colgroup> element.
10. <tfoot>
The <tfoot> element is used to store the footer row of a table. This element is used to add necessary information at the bottom of the table, such as totals or subtotals.
How to Create a Table in PHP
The source examples below should be read as instructional material; avoid copying user data directly into HTML. When accessing the database, use parameterized queries and output escaping. create a MySQL database This discusses different environments and requires caution as some SQL instances can delete data. Keep a backup before experimenting.
To create a table in PHP, you can use HTML code to create the tags <table>, <tr>, <th>, and <td>. Here’s a code example for creating a simple table in PHP:
<?php
echo "<table>";
echo "<tr>";
echo "<th>Nama</th>";
echo "<th>Umur</th>";
echo "</tr>";
echo "<tr>";
echo "<td>John Doe</td>";
echo "<td>25</td>";
echo "</tr>";
echo "</table>";
?>
The output of the code above is a simple table with two columns (Name and Age) and one row of data (John Doe and 25).
You can also use a loop, such as a foreach loop, to add dynamic data to the table. For example:
<?php
$data = array(
array(“Name” => “John Doe”, “Age” => 25),
array(“Name” => “Jane Smith”, “Age” => 30),
array(“Name” => “Bob Johnson”, “Age” => 35)
);
echo “<table>”;
echo “<tr>”;
echo “<th>Name</th>”;
echo “<th>Age</th>”;
echo “</tr>”;
foreach ($data as $row) {
echo “<tr>”;
echo “<td>” . $row[“Name”] . “</td>”;
echo “<td>” . $row[“Age”] . “</td>”;
echo “</tr>”;
}
echo “</table>”;
?>
The output of the code above is a table with three rows of data taken from the $data array.
When creating tables in PHP, you can also use CSS to style the table’s appearance. You can add class or id attributes to HTML elements and style the table using CSS. For example:
CSS:
<style>
.table {
border-collapse: collapse;
}
.table th, .table td {
border: 1px solid black;
padding: 5px;
}
</style>
PHP:
<?php
echo "<table class='table'>";
echo "<tr>";
echo "<th>Nama</th>";
echo "<th>Umur</th>";
echo "</tr>";
echo "<tr>";
echo "<td>John Doe</td>";
echo "<td>25</td>";
echo "</tr>";
echo "</table>";
?>
By using the class attribute on the <table> element, you can style the table using CSS.
PHP Table Rendering Example from Array with Secure Output
For example, a store’s stock list is stored in an array. The following example uses htmlspecialchars() to display product names as plain text; stock values are converted to numbers. There is no database connection or change to production data.
<?php
$items = [
['nama' => 'Mouse', 'stok' => 8],
['nama' => 'Keyboard', 'stok' => 12]
];
?>
<table>
<caption>Daftar Stok</caption>
<thead><tr><th scope="col">Produk</th><th scope="col">Stok</th></tr></thead>
<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td><?= htmlspecialchars($item['nama'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></td>
<td><?= (int) $item['stok'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Documentation PHP htmlspecialchars explains HTML escaping. When using SQL queries, learn PDO prepared statements; both mitigate different risks and are not substitutes for each other.
Responsive and Accessible Table Principles
| Element | Utility | Practice |
|---|---|---|
| caption | Explaining the contents of the table | Use short descriptions |
| head | Table header | Use the appropriate th and scope |
| tbody | Data rows | Render through loop |
| td | Table values | Dynamic output escape |
Don’t hide important columns just to fit the mobile view. Use horizontal scrolling when necessary and maintain headers. For web-based applications WordPress, the content structure can be arranged through WordPress post editor And the difference between pages and posts; it is different from tables created programmatically in PHP.
Troubleshooting and Safe Practices
- If the markup is messy, check the opening and closing tags and the number of columns per line.
- If the data is incorrect, check the array or query source before checking the CSS.
- If the value contains angle brackets, escape it as HTML entities in the text context.
- If the data is thousands of rows, consider server-side pagination and limited queries.
- If the application displays an error, record the details in a secure log and do not divulge credentials.
Site problems don’t always stem from PHP: server maintenance can temporarily restrict access, load balancing can share the load, while proxy server And IP address related to the network. Before launching a public page, evaluate technical SEO, crawler access, And URL slug when a table appears on a page that a search engine should find.
Frequently Asked Questions (FAQ)
How to create a table in PHP?
Prepare the data, render the HTML table markup, then use a PHP loop to create dynamic rows.
Does a table need a database?
No. Tables can be created from static arrays; a new database is required if data is to be stored and retrieved from there.
What is the function of thead and tbody?
thead groups the headers, while tbody contains rows of data.
What is the function of the scope?
Helps explain the relationship of header cells to rows or columns for readers with assistive technology.
Why need htmlspecialchars()?
To convert special characters in dynamic text into HTML entities before displaying.
Does htmlspecialchars prevent all attacks?
No. Input validation, parameterized queries, and other safeguards are still required.
What is the difference between HTML tables and SQL tables?
HTML tables display data to visitors, while SQL tables store structured data in a database.
How to make a responsive table?
Choose CSS that can accommodate tables on small screens without losing important information.
How to display very large data?
Use pagination and limit queries on the server rather than loading everything at once.
Does PHP table auto sort?
No. Interactive sorting requires additional server logic or JavaScript.
External References
- PHP Manual — htmlspecialchars
- PHP Manual — PDO prepared statements
- MDN — HTML Table
- W3C WAI — Accessible tables