PHP : MySQL Connect

First, we need to make connection between PHP & MySQL Server. Then, PHP will be able to interact with MySQL database and access data.

PHP-MySQL connection using MySQLi functions:

MySQLi stands for MySQL improved. The MySQLi extension was introduced with PHP version 5.0.0. We will interact with MySQL using various PHP functions starting with “mysqli_”.

mysqli_connect()

function is used to create a new connection to the MySQL server. It will return false (bool) if connection is not established, else it will return MySQL object information.

Example :

mysqli_connect(server, username, password); 

ParametersDescription
serverUse MySQL Server name along with optional port number, for example: “hostname:port”. Use localhost for local machine socket.
usernameUse MySQL username (default username is local is “root” or check in your MySQL configuration.)
passwordUse MySQL password (default username is local is blank “” or check in your MySQL configuration.)

Example of Connecting PHP with MySQL Database

Now we will see how to to make PHP and MySQL Connection. Let us suppose MySQL server/host name is “localhost”, username is “root” and password is “” (blank). Then we can use following example for Connecting PHP with MySQL Database.

<?php
/**
 * Create Database Connection
 */
 
$database_server = 'localhost';
$database_username = 'root';
$database_password = '';
 
// Create connection using mysqli_connect()
$conn = mysqli_connect($database_server, $database_username, $database_password);
 
// If $conn is false, connection is failed
if (!$conn ) {
  die("Failed to connect to MySQL: " . mysqli_connect_error());
}
 
echo "Database Connected Successfully.";
 
?>

Description of above example

  • First, we will pass required MySQL Server information (host/username/password) in mysqli_connect() function.
  • If information is correct, it will create a database connection & assign connection information in $conn variable.
  • If server information is not correct, it will assign false to $conn variable
  • Now, we will print success or failure message based on $conn variable information.
  • mysqli_connect_error() function returns the error message from the last connection error, if any error occurred.
  • mysqli_close() function closes a previously created database connection.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.