English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MySQL Connection

Connecting using mysql binary mode

You can enter the mysql command prompt in binary mode to connect to the MySQL database.

Online Example

The following is a simple example of connecting to the mysql server from the command line:

[root@host]# mysql -u root -p
Enter password:******

After logging in successfully, the mysql> command prompt will appear, where you can execute any SQL statements.

The output after executing the above command is as follows:

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2854760 to server version: 5.0.9
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

In the above example, we logged into the mysql server using the root user, of course, you can also log in using other mysql users.

If the user has sufficient permissions, any user can perform SQL operations in the mysql command prompt.

You can exit the mysql> command prompt using the exit command, as shown below:

mysql> exit
Bye

Connecting to MySQL using PHP script

PHP provides the mysqli_connect() function to connect to the database.

This function has 6 Parameters return a connection identifier after successfully linking to MySQL, or FALSE if the operation fails.

Syntax

mysqli_connect(host, username, password, dbname, port, socket);

Parameter description:

ParameterDescription
hostOptional. Specify the hostname or IP address.
usernameOptional. Specify the MySQL username.
passwordOptional. Specify the MySQL password.
dbnameOptional. Specify the default database to use.
portOptional. Specify the port number to try to connect to the MySQL server.
socketOptional. Specify the socket or the named pipe to be used.

You can use the PHP mysqli_close() function to disconnect from the MySQL database.

This function has only one parameter, which is the MySQL connection identifier returned by the mysqli_connect() function after a successful connection is created.

Syntax

bool mysqli_close ( mysqli $link )

This function closes the non-persistent connection associated with the specified connection identifier to the MySQL server. If no link_identifier is specified, the last opened connection is closed.

Tip:It is usually not necessary to use mysqli_close(), because non-persistent connections that have been opened will automatically close after the script execution is completed.

Online Example

You can try the following examples to connect to your MySQL server:

<?php
$dbhost = 'localhost';  // MySQL Server Host Address
$dbuser = 'root';            // MySQL Username
$dbpass = '123456';          // MySQL Username Password
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('Could not connect: ' . mysqli_error());
}
echo 'Database connection successful!';
mysqli_close($conn);
?>