Skip to content
PHP Logo

How can PHP be used to access a SQL server and display a list of elements?

To access a SQL server and display a list of elements using PHP, you can use the PDO (PHP Data Objects) extension to connect to the database and execute queries. You can fetch the results from the database and display them in a list format using PHP.

php
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Query to fetch elements from the database
    $stmt = $conn->query("SELECT * FROM table_name");
    
    // Displaying elements in a list
    echo "<ul>";
    while ($row = $stmt->fetch()) {
        echo "<li>" . $row['column_name'] . "</li>";
    }
    echo "</ul>";

} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>