MySQL Connection
Connecting Using MySQL Binary
You can connect to the MySQL database by entering the MySQL command prompt using the MySQL binary method.
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 successful login, the mysql> command prompt window will appear, where you can execute any SQL statements.
After executing the above command, 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 logged in to the MySQL server using the root user, but 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 window.
To exit the mysql> command prompt window, you can use 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 and returns a connection identifier upon successful connection to MySQL, or FALSE on failure.
Syntax
mysqli_connect(host, username, password, dbname, port, socket);
Parameter Description:
Parameter | Description |
---|---|
host | Optional. Specifies the hostname or IP address. |
username | Optional. Specifies the MySQL username. |
password | Optional. Specifies the MySQL password. |
dbname | Optional. Specifies the default database to use. |
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 the PHP mysqli_close() function to disconnect from the MySQL database.
This function takes one parameter, which is the MySQL connection identifier returned by the mysqli_connect() function upon successful connection.
Syntax
bool mysqli_close ( mysqli $link )
This function closes the non-persistent connection to the MySQL server associated with the specified connection identifier. If no link_identifier is specified, it closes the last opened connection.
Note: Usually, there is no need to use mysqli_close(), as non-persistent open connections are automatically closed at the end of the script execution.
Example
You can try the following example to connect to your MySQL server:
Connect to MySQL
<?php
$dbhost = 'localhost'; // mysql server host address
$dbuser = 'root'; // mysql username
$dbpass = '123456'; // mysql user password
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Database connection successful!';
mysqli_close($conn);
?>