MySQLi Tutorial MySQLi References

mysqli $connect_error Property



The mysqli::$connect_error / mysqli_connect_error() function returns the error message from the last connection attempt.

Syntax

//Object-oriented style
$mysqli->connect_error;

//Procedural style
mysqli_connect_error()

Parameters

No parameter is required.

Return Value

Returns a string that describes the error. null is returned if no error occurred.

Example: Object-oriented style

The example below shows the usage of mysqli::$connect_error property.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "fake_user", "password", "database");
if ($mysqli->connect_error) {
  echo "Connection error: ". $mysqli->connect_error;
  exit();
}

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

The output of the above code will be similar to:

Connection error: Access denied for user 'fake_user'@'localhost' (using password: YES)

Example: Procedural style

The example below shows the usage of mysqli_connect_error() function.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "fake_user", "password", "database");
if (mysqli_connect_error()) {
  echo "Connection error: ". mysqli_connect_error();
  exit();
}

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

The output of the above code will be similar to:

Connection error: Access denied for user 'fake_user'@'localhost' (using password: YES)

❮ MySQLi Functions Reference