What are common reasons for being unable to connect to MySQL in PHP applications?
One common reason for being unable to connect to MySQL in PHP applications is incorrect database credentials, such as the hostname, username, password, or database name. Another reason could be that the MySQL server is not running or is inaccessible from the PHP server. To solve this issue, double-check the database credentials and ensure that the MySQL server is running and accessible.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>