How do you fetch data from a MySQL table in PHP

To fetch data from a MySQL table in PHP, you can follow the example below which demonstrates how to connect to a MySQL database and retrieve data from a table.

<?php // Database connection parameters $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "database_name"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // SQL query to fetch data $sql = "SELECT id, name, email FROM users"; $result = $conn->query($sql); // Check if results exist if ($result->num_rows > 0) { // Output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } } else { echo "0 results"; } // Close connection $conn->close(); ?>

PHP MySQL fetch data database connection SQL query