MySQL connection


MySQL connection

Use mysql binary mode to connect

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

Related video tutorials:

  • ##MySQL connection database

  • Create MySQLi objects and Database connection

  • Integration of MySQL and PHP: enabling PHP to handle the database

##Example

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

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

After successful login, the mysql> command prompt window will appear, on which you can execute any SQL statement.

After the above command is executed, the successful login output 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 used the root user to log in to the mysql server. Of course, you can also use other mysql users to log in.

If the user rights are sufficient, any user can perform SQL operations in the mysql command prompt window.

Exit mysql> You can use the exit command in the command prompt window, as shown below:

mysql> exitBye

Use PHP script to connect to MySQL

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

This function has 6 parameters, returns the connection ID after successfully connecting to MySQL, and returns FALSE upon failure.

Syntax

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

Parameter description:

ParametersDescription
host Optional. Specify the hostname or IP address.
username Optional. Specifies the MySQL username.​
password ​ Optional. Specifies the MySQL password.​
dbname Optional. Specifies the database to use by default.
port Optional. Specifies the port number to attempt to connect to the MySQL server.
socket Optional. Specifies the socket or named pipe to use.​

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

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

Syntax

bool mysqli_close ( mysqli $link )

This function closes the non-persistent connection to the MySQL server associated with the specified connection ID. If link_identifier is not specified, the last open connection is closed.

Tip: There is usually no need to use mysqli_close() because the opened non-persistent connection will be automatically closed after the script is executed.

Example

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

<?php
$dbhost = 'localhost:3306'; // mysql server host address
$dbuser = 'root'; mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Database connection successful! ';
mysqli_close($conn);
?>