Monday, 24 September 2018

How to connect MySQL database using MySQLi procedural function

Hello friends, my previous article "MySQLi - An improved and enhanced MySQL extension" provides an introduction about the MySQLi extension and its features. This article demonstrates how to create connection with a MySQL database using MySQLi extension. MySQLi provides two interfaces (Procedural and Object Oriented) for connecting and interacting with MySQL, this article demonstrate only about the procedural way to connect to MySQL server.


For connecting to MySQL server MySQLi extension provides mysqli_connect() function. The detail about mysqli_connect() is given below :

mysqli_connect()

mysqli_connect() is used to create a connection to MySQL server. On successful connection, it returns an object which represents connection for other mysqli_* functions and FALSE on failure.

Syntax : mysqli_connect(host_name, username, password, db_name, port, socket);
Description :
host_name : Specifies a host name or an IP address of MySQL server.
username : Specifies the MySQL Username
password : Specifies the MySQL Password
db_name : Specifies the default database to be used
port : Specifies the port number to connect to the MySQL server
socket : Specifies the socket name or named pipe

Description :
The mysqli_connect() function create a connection to MySQL Server specified by host_name. It can be either a host name or an IP address. If connection created successfully, the mysqli_connect() function returns an object which represents the connection to the database, and on failure function return FALSE.

The username and password parameters are used for connecting to the MySQL server. If the password field, leave blank or NULL, then server authenticates the user within those user records for which password is not set.

db_name parameter specifies the default database to be used for executing further queries.

The port parameter used to open the connection on specified port number, while the socket parameter specifies the name of socket or named pipe.

Below is the script to connect to MySQL server using mysqli_connect() :

  1. <?php
  2. $host_name = "localhost";
  3. $username = "username";
  4. $password = "password";
  5. $database = "test";//database name
  6. // Create connection
  7. $con = mysqli_connect($host_name, $username, $password, $database);
  8. // Check connection
  9. if (!$con) {
  10. echo "Error: " . mysqli_connect_error(); die;
  11. }
  12. echo "Connection to database : ".$database." created successfully on server : ".mysqli_get_host_info($con);
  13. ?>

Output : Connection to database : test created successfully on server : Localhost via UNIX socket

0 comments:

Post a Comment