Write a PHP script that connects to a MySQL database and fetches data from a table.

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "example_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch data from a table
$result = $conn->query("SELECT * FROM users");

// Display data
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "ID: {$row['id']}, Name: {$row['name']}, Email: {$row['email']}<br>";
    }
} else {
    echo "No results found";
}

// Close connection
$conn->close();
?>

 

Post your Answer