PHP & MySQL Tutorial PHP & MySQL References

PHP & MySQL - Connect to MySQL



The MySQLi extension of PHP allows you to access MySQL database servers. It is designed to work with MySQL version 4.1 and above.

Installation & Runtime Configuration

The MySQLi extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0.

For installation details, go to: https://php.net/manual/en/mysqli.installation.php

For runtime configuration details, go to: https://php.net/manual/en/mysqli.configuration.php

mysqli_connect() function

To connect to the MySQL server, mysqli_connect() function can be used. The syntax for using this function is mentioned below:

//Object-oriented style
public mysqli::connect(hostname, username, password, 
                       database, port, socket)

//Procedural style
mysqli_connect(hostname, username, password, 
               database, port, socket)

Parameters

hostname Optional. Specify the host name or an IP address. Passing the null value or "localhost" to this parameter, the local host is assumed.
username Optional. Specify the MySQL user name.
password Optional. Specify the MySQL password. This allows the username to be used with different permissions (depending on if a password is provided or not).
database Optional. If provided will specify the default database to be used when performing queries.
port Optional. Specify the port number to attempt to connect to the MySQL server.
socket Optional. Specify the socket or named pipe that should be used.

Connect to MySQL Database - Object-oriented style

The example below demonstrates how to connect to the MySQL database using object-oriented style.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDatabase";

//establishing connection 
$mysqli = new mysqli($servername, $username, $password, $dbname);

//checking connection
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

echo "Connected successfully.";

//closing the connection
$mysqli->close();
?>

The output of the above code will be:

Connected successfully.

Connect to MySQL Database - Procedural style

The same can be achieved using procedural style with following script:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDatabase";

//establishing connection 
$mysqli = mysqli_connect($servername, $username, $password, $dbname);

//checking connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

echo "Connected successfully.";

//closing the connection
mysqli_close($mysqli);
?>

The output of the above code will be:

Connected successfully.

Complete PHP MySQLi Reference

For a complete reference of all properties, methods and functions of PHP MySQLi extension, see PHP MySQLi Reference.