PHP database connection fails due to the following reasons: the database server is not running, the host name or port is incorrect, the database credentials are incorrect, or the appropriate permissions are missing. Solutions include: starting the server, checking the hostname and port, verifying credentials, modifying permissions, and adjusting firewall settings.
#Why does my PHP database connection fail?
Introduction
It is common to encounter errors when connecting to a database using PHP. This article describes common problems connecting to databases and their solutions.
Common Errors
Cause
These errors may have the following causes:
Practical case
Error: Unable to connect to the MySQL server.
Cause: The database server is not running.
Solution: Start the MySQL server.
Code sample:
<?php // 检查 MySQL 服务器是否已启动 $mysqli = new mysqli("localhost", "root", "password"); // 如果连接失败,打印错误信息 if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: " . $mysqli->connect_error; } else { echo "Connected to MySQL successfully!"; } ?>
Other solutions
The above is the detailed content of Why does my PHP database connection fail?. For more information, please follow other related articles on the PHP Chinese website!