What are common issues when trying to establish a connection to a MySQL database using PHP?
Common issues when trying to establish a connection to a MySQL database using PHP include incorrect database credentials, server connectivity issues, and missing PHP extensions such as mysqli. To solve this, double-check the database host, username, password, and database name for accuracy. Ensure that the MySQL server is running and accessible from the PHP server. Lastly, make sure the mysqli extension is enabled in the PHP configuration.
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'dbname';
// Create connection
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>