saftutorials.com
MYSQL CONNECT

Open Database Connection

PHP provides us a function by using this function we can open a database connection. This is the function mysql_connect(), it takes five parameters and returns MYSQL link identifier if success or return FALSE if not a success.


This is the syntax of mysql_connect function of PHP

mysql_connect(server_name,user_name,password,new_link,client_flag)


Server_name  - This parameter is optional.Host name of running database server if not specified then the default value is localhost.

User_name    - This parameter is optional.Username for accessing the database if not specified then the default is the name of the user that the server process.Commonly it is the root.

Password     - This parameter is optional.Password of the user for accessing the database if not specified then the default is an empty password.

New_link     - This parameter is optional.If you call the mysql_connect() function the second time with the same argument then no new connection will be established and the identifier of the already opened connection will be returned.

Client_flag  - This parameter is optional.This is the combination of following contents.

                  MYSQL_CLIENT_SSL                      - This is use for SSL encryption

 MYSQL_CLIENT_COMPRESS            - This is use for compression protocol

 MYSQL_CLIENT_IGNORE_SPACE     - This allow space after function names

 MYSQL_CLIENT_INTERACTIVE        - This allow interactive timeout seconds of inactivity before closing the connection

   

Close Database Connection

PHP also provides us a function by using this function we can close a database connection. This is the function mysql_close() and it takes connection resource returned by mysql_connect() function as a parameter. This function return TRUE value on success and FALSE value on failure.


This is the syntax of the mysql_connect() function of PHP

mysql_close(connection)

connection  - This parameter is required.And this is the connection resource or link identifier which is returned by mysql_connect() function on success.


Below is an example of open and close database connection

<?php
$database_host = 'localhost:3036';
$database_user = 'guest';
$database_pass = 'guest123';
$conn = mysql_connect($database_host, $database_user, $database_pass);
if(! $conn ) {
  die('Could not connect: ' . mysql_error());
}else{
 echo 'Connected successfully';
}
// After inserting, deleting, updating and fetching data from database close the database connection.
mysql_close($conn);
?>

The above PHP code produces the following results if host, user, and password is correct

Output: Connected successfully


And if some of the values wrong to print the below value and stop the execution

Output: Could not connect: with error details


Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic