• PHP Video Tutorials

PHP mysqli_connect_error() Function



Definition and Usage

During the attempt to connect to a MySQL server, if an occurs, the mysqli_connect_error() function returns the description of the error occurred (during the last connect call).

Syntax

mysqli_connect_error()

Parameters

This method doesn't accept any parameters.

Return Values

PHP mysqli_connect_error() function returns an string value representing the description of the error from the last connection call, incase of a failure. If the connection was successful this function returns Null.

PHP Version

This function was first introduced in PHP Version 5 and works works in all the later versions.

Example

Following example demonstrates the usage of the mysqli_connect_error() function (in procedural style) −

<?php
   //Creating a connection
   $con = @mysqli_connect("localhost", "root", "wrong_password", "mydb");

   //Connection Error
   $error = mysqli_connect_error($con);
   print("Error: ".$error);
?>

This will produce following result −

Error: Access denied for user 'root'@'localhost' (using password: YES)

Example

In object oriented style the syntax of this function is $con -> connect_error. Following is the example of this function in object oriented style −

<?php
   //Creating a connection
   $con = @new mysqli("localhost", "root", "wrong_password", "mydb");

   //Connection Error
   $error = $con->connect_error;
   print("Error: ".$error);
?>

This will produce following result −

Error: Access denied for user 'root'@'localhost' (using password: YES)

Example

Following example demonstrates the behaviour of the mysqli_connect_error() function incase of a successful connection −

<?php
   //Creating a connection
   $con = @mysqli_connect("localhost", "root", "password", "mydb");
   
   //Connection Error
   $error = mysqli_connect_error();
   if(!$con){
      print("Connection Failed: ".$error);
   }else{
      print("Connection Established Successfully");
   }
?>

This will produce following result −

Connection Established Successfully

Example

<?php
   $connection = @mysqli_connect("localhost","root","wrong_pass","wrong_db");
   
   if (!$connection){
      die("Connection error: " . mysqli_connect_error());
   }
?>

This will produce following result −

Connection error: Access denied for user 'root'@'localhost' (using password: YES)
php_function_reference.htm
Advertisements