Home > Database > Mysql Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-24 12:52:31
Original
428 people have browsed it

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

Displaying Data from SQL Database in PHP/HTML Table

In PHP, connecting to a MySQL database and displaying data from it into an HTML table can be achieved using the following steps:

<code class="php">$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');

$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . htmlspecialchars($row['name']) . "</td><td>" . htmlspecialchars($row['age']) . "</td></tr>";  //$row['index'] the index here is a field name
}

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

mysql_close(); //Make sure to close out the database connection</code>
Copy after login

In this code:

  • We connect to the database using mysql_connect(), providing the host, username, and (empty) password.
  • We select the hrmwaitrose database using mysql_select_db().
  • We execute an SQL query to retrieve all rows from the employee table using mysql_query().
  • We then use a while loop to iterate through the results, generating HTML table rows () with data columns () for each row.
  • We escape the data using htmlspecialchars() to prevent XSS attacks.
  • Finally, we close the table and the database connection.

This code provides a simple template for displaying data from a MySQL database into an HTML table in PHP. Please note that mysql_fetch_array is deprecated in PHP 7.0.0 and later, so you may need to use mysqli_fetch_array() instead.

The above is the detailed content of How to Display Data from SQL Database in 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
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!