Home > Database > Mysql Tutorial > body text

How to Display SQL Database Data in PHP/HTML Tables?

Linda Hamilton
Release: 2024-10-24 14:53:02
Original
730 people have browsed it

How to Display SQL Database Data in PHP/HTML Tables?

Displaying SQL Database Data in PHP/HTML Tables

Question:

How can I display data from a SQL table on a HTML or PHP table?

Background:

You have a database on MySQL and want to display data from the "employee" table on a web page.

Solution:

PHP provides functionality to establish a connection to a MySQL database. Here's a code snippet that demonstrates how to achieve this:

<code class="php">$connection = mysql_connect('localhost', 'root', ''); // Password is left blank
mysql_select_db('hrmwaitrose');

$query = "SELECT * FROM employee"; // SQL statement
$result = mysql_query($query);

echo "<table>"; // Start HTML table

while ($row = mysql_fetch_array($result)) {
    echo "<tr><td>" . htmlspecialchars($row['name']) . "</td><td>" . htmlspecialchars($row['age']) . "</td></tr>";
}

echo "</table>"; // End HTML table

mysql_close(); // Close database connection</code>
Copy after login

In the while loop, each row of the SQL query result is converted into a table row in HTML.

Note:

  • The "mysql_fetch_array" function is now deprecated in PHP 7.0.0 and above. Consider using "mysqli_fetch_array" instead.
  • Always sanitize user input before inserting it into a database to prevent SQL injection attacks.

The above is the detailed content of How to Display SQL Database Data in PHP/HTML Tables?. 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
Latest Articles by Author
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!