Home > Database > Mysql Tutorial > body text

How to Display SQL Database Data in a PHP/HTML Table?

DDD
Release: 2024-10-24 16:36:02
Original
360 people have browsed it

How to Display SQL Database Data in a PHP/HTML Table?

Displaying Data from a SQL Database in a PHP/HTML Table

When working with a MySQL database, there may be instances where you need to display table data on a PHP/HTML table. This can be achieved through the following steps:

<code class="php"><?php
// Connect to the MySQL database
$connection = mysql_connect('localhost', 'root', ''); // Replace 'root' with your database username and leave password blank if none exists
mysql_select_db('hrmwaitrose'); // Replace 'hrmwaitrose' with your database name

// Execute the query to retrieve data from the 'employee' table
$query = "SELECT * FROM employee"; // Remove the semicolon (;) from the SQL query
$result = mysql_query($query);

// Create a new HTML table
echo "<table>";

// Retrieve each row of data from the query result
while ($row = mysql_fetch_array($result)) {
    // Create a new table row for each employee record
    echo "<tr><td>" . htmlspecialchars($row['name']) . "</td><td>" . htmlspecialchars($row['age']) . "</td></tr>";
}

// Close the HTML table
echo "</table>";

// Close the MySQL connection
mysql_close();
?></code>
Copy after login

In this script, the mysql_connect function establishes a connection to the MySQL database, while mysql_select_db selects the specific database to work with. The mysql_query function executes the SQL query to retrieve data from the 'employee' table.

The mysql_fetch_array function retrieves each row of data from the query result and assigns the values to an array. The htmlspecialchars function is used to escape any special characters in the data returned from the database to prevent potential security vulnerabilities.

The echo statements output the HTML code to create a table with the employee data. The while loop continues until all rows from the query result have been processed.

Please note that the mysql_fetch_array function is deprecated in PHP versions 5.5.0 and above, so it's recommended to use mysqli_fetch_array instead for improved security.

The above is the detailed content of How to Display SQL Database Data in a PHP/HTML Table?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!