Databases are an integral part of development using PHP. The first step to connecting to the database is usually to use the connect() function. Although it is more recommended to use PDO or MySQLi, understanding the usage of mysql_connect() or mysqli_connect() is still of great benefit to understanding the underlying logic of database operations. This article will use mysqli_connect() as an example to analyze in detail how to connect to the MySQL database through it.
Before you start writing code, make sure you meet the following conditions:
PHP and MySQL are installed (PHP 7.0 and above are recommended).
Have the connection information of the database, including the host name, user name, password, and database name.
MySQL service has been enabled on the server or local environment.
mysqli_connect(host, username, password, dbname, port, socket);
Parameter description:
host : The MySQL server address, usually localhost or IP address.
username : database username.
password : database password.
dbname : The name of the database to be connected.
port : Connection port, default is 3306.
socket : optional, Unix socket or named pipe.
Here is a complete example of the connection code:
<?php
$host = 'localhost';
$user = 'root';
$pass = 'your_password';
$dbname = 'example_db';
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
die('Connection failed: ' . mysqli_connect_error());
}
echo 'Connection successfully';
?>
If you want to access a URL in your browser to execute this script, make sure you have placed the script in your server directory, for example:
http://www.m66.net/connect_test.php
Connection timeout:
Check whether the database service is running.
Confirm whether the port number is correct.
Error in username or password:
Make sure the username and password are correct.
If you are using a remote database, make sure that the user has remote access.
The database does not exist:
Use SHOW DATABASES; confirm whether the target database exists.
Pay attention to case sensitivity issues.
The object-oriented writing method is clearer and more in line with modern development habits:
<?php
$mysqli = new mysqli('localhost', 'root', 'your_password', 'example_db');
if ($mysqli->connect_error) {
die('Connection failed (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
echo 'Connection successfully';
?>
It can also be executed through a URL, such as: