Home  >  Article  >  Database  >  How to Display MySQL Database Data in a PHP/HTML Table?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 17:51:02836browse

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

Displaying MySQL Database Data in a PHP/HTML Table

MySQL databases are widely used in web development for storing and managing data. To access and display data from a MySQL database in a PHP/HTML table, follow these steps:

  1. Connect to the MySQL Database:
<code class="php">$connection = mysql_connect('localhost', 'root', ''); // Replace with your credentials
mysql_select_db('hrmwaitrose');</code>
  1. Prepare the SQL Query:

Construct the SQL query to retrieve the data from the desired table (e.g., "employee").

<code class="php">$query = "SELECT * FROM employee";</code>
  1. Execute the Query and Store the Results:
<code class="php">$result = mysql_query($query);</code>
  1. Generate the HTML Table:
<code class="php">echo "<table border='1'>";
echo "<tr><th>Name</th><th>Age</th></tr>";</code>
  1. Fetch the Data Row by Row and Add to Table:

Using a loop, fetch each row of data from the result set and add it to the HTML table.

<code class="php">while ($row = mysql_fetch_array($result)) {
  echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";
}</code>
  1. Close the Table and Database Connection:
<code class="php">echo "</table>";
mysql_close($connection);</code>

This code will create an HTML table with the data from the employee table. Note that you may need to adjust the column names and table styles as per your requirement.

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

Statement:
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