PHP's failure to connect to MySQL may be caused by a variety of reasons. This article will analyze several common situations and solutions.
First, check whether the database connection information in the PHP code connecting to MySQL is correct. Includes hostname, username, password, and database name. If this information is incorrect, you will be unable to connect to the MySQL database.
The following is a basic MYSQL connection example:
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } echo "连接成功"; ?>
In it, "localhost" is the host name, "username" is the MySQL username, and "password" is the MySQL password.
If the MySQL service is not running, then PHP cannot connect to the MySQL database. If you find that your code cannot connect to the MySQL database, check the running status of the service.
If you are using a Linux system, you can use the following command to start the MySQL service:
sudo /etc/init.d/mysql start
If you are using a Windows system, you can find the MySQL service in the service and start it.
In some cases, firewall or network issues may prevent you from connecting to the MySQL database. If your server is protected through a firewall, you need to add the MySQL port. By default, MySQL uses TCP port 3306. You need to make sure this port is not blocked.
If you have determined that the MySQL port is open and still cannot connect to the MySQL database, please try to ping the MySQL host address to check whether you can successfully connect to the MySQL host. If the network is unreachable, you cannot connect to the MySQL server.
Finally, connecting to MySQL in PHP requires using the MySQL extension. You cannot connect to a MySQL database if the required MySQL extensions are not installed or enabled in PHP. You can check if the MySQL extension is enabled in the php.ini file.
In the [extension] section of the php.ini file, you need to check whether the MySQL extension is enabled, as shown below:
;extension=mysql.so
If there is no semicolon in front and the extension name is marked, then Indicates that the extension has been enabled. If the semicolon is commented out, it means that the extension is not enabled.
If the extension is not enabled, download the corresponding MySQL extension and add it to the [extension] section in the php.ini file.
Summary
Sometimes you may have difficulty connecting to MySQL in PHP, but usually these problems are caused by simple reasons. Checking the database connection information, whether the MySQL service is running, firewall or network issues, and whether the PHP extension is enabled can help you solve the problem in the shortest time.
The above is the detailed content of PHP cannot connect to mysq. For more information, please follow other related articles on the PHP Chinese website!