Current Location: Home> Latest Articles> Standard process for connecting to MySQL databases using connect()

Standard process for connecting to MySQL databases using connect()

M66 2025-05-29

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.

1. Preparation

Before you start writing code, make sure you meet the following conditions:

  1. PHP and MySQL are installed (PHP 7.0 and above are recommended).

  2. Have the connection information of the database, including the host name, user name, password, and database name.

  3. MySQL service has been enabled on the server or local environment.

2. Use mysqli_connect() to connect to the database

grammar

 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.

Sample code

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

3. Common errors and troubleshooting methods

  1. Connection timeout:

    • Check whether the database service is running.

    • Confirm whether the port number is correct.

  2. 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.

  3. The database does not exist:

    • Use SHOW DATABASES; confirm whether the target database exists.

    • Pay attention to case sensitivity issues.

4. Use object-oriented connection (recommended)

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: