W3docs

real_connect

In this article, we will discuss the mysqli_real_connect() function in PHP, which is used to establish a connection to a MySQL database.

In this article, we will discuss the real_connect() method in PHP, which is used to establish a connection to a MySQL database. (The procedural equivalent is mysqli_real_connect().)

Introduction to the real_connect() method

The real_connect() method is a built-in PHP method used to establish a connection to a MySQL database. It is similar to mysqli_connect(), but provides more control over the connection process, such as explicit error handling and optional parameters like client flags.

How to use the real_connect() method

Using the real_connect() method is straightforward. Here's an example demonstrating the object-oriented approach:

<?php
$mysqli = mysqli_init();

if (!$mysqli) {
    die('mysqli_init failed');
}

if (!$mysqli->real_connect('localhost', 'username', 'password', 'database')) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

In this example, we first create a new MySQLi object using the mysqli_init() function. We then verify the object was created successfully. If it was, we call the real_connect() method on the $mysqli object to establish a connection to the MySQL database. The method accepts the following parameters in order:

  • server: The hostname or IP address (e.g., 'localhost').
  • username: The MySQL user (e.g., 'username').
  • password: The user's password (e.g., 'password').
  • database: The target database name (e.g., 'database').
  • port: The port number (default: 3306).
  • socket: The socket or named pipe (optional).
  • flags: Client flags for connection options (optional).

If the connection fails, we output an error message using the die() function. If the connection is successful, we output a success message using the echo statement. Finally, we close the connection using the close() method.

Conclusion

In conclusion, the real_connect() method is an essential tool for establishing a connection to a MySQL database in PHP. By understanding how to use the method, you can connect to a database and begin working with data, executing queries, and retrieving result sets.

Practice

Practice

What can be done with the mysqli_real_connect() function in PHP?