← Back to PHP Course | Chapter 11: Database | Lesson 2 of 21

PHP MySQLi Connection

A MySQLi connection is like dialing a phone number to reach the database. You give PHP the address, name, and password, and it opens a line so you can ask questions.
Syntax
php
$conn = mysqli_connect($host, $user, $password, $database);   // procedural
$conn = new mysqli($host, $user, $password, $database);        // object-oriented

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

mysqli_close($conn);

What is MySQLi?

mysqli_connect($host, $user, $password, $database) opens a connection to a MySQL server using the procedural style of the mysqli extension, returning a connection object you'll pass to later query functions.

Example: What is MySQLi?

php
<?php
// SQLite3 stands in for mysqli_connect() here -- on your own server:
// $conn = mysqli_connect("localhost", "root", "", "my_app");
$conn = new SQLite3(':memory:');
echo "Connection established";
?>

Closing the Connection

The object-oriented style instead creates a new mysqli($host, $user, $password, $database) instance, and most modern PHP code prefers this style since it reads more naturally alongside other object-oriented database code.

Example: Closing the Connection

php
<?php
// Object-oriented style: $conn = new mysqli($host, $user, $password, $database);
$conn = new SQLite3(':memory:');
echo get_class($conn);
?>

Handling Connection Errors

Always check the connection for errors immediately after connecting, using mysqli_connect_error() or the object's ->connect_error property, so a bad password or unreachable host fails with a clear message rather than a cascade of confusing later errors.

Example: Handling Connection Errors

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$conn`
$conn = new SQLite3(':memory:');
// Check whether `!$conn`
if (!$conn) {
    // Print "Connection failed" to the output
    echo "Connection failed";
// Otherwise, run this branch
} else {
    // Print "Connected successfully" to the output
    echo "Connected successfully";
}
?>

Selecting a Database

Connection credentials (host, username, password) should never be hardcoded directly in a script committed to version control — storing them in environment variables or a gitignored config file keeps secrets out of your repository.

Example: Selecting a Database

php
<?php
// Declare `$host`, set to `getenv('DB_HOST') ?: 'localhost'`
$host = getenv('DB_HOST') ?: 'localhost';
// Declare `$user`, set to `getenv('DB_USER') ?: 'root'`
$user = getenv('DB_USER') ?: 'root';
// Print "Connecting to $host as $user (credentials from environment, not hardcoded)" to the output
echo "Connecting to $host as $user (credentials from environment, not hardcoded)";
?>

Executing a Simple Query

Closing a connection explicitly with mysqli_close() or ->close() is good practice, though PHP will also close any open connections automatically at the end of the script's execution.

Example: Executing a Simple Query

php
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$conn`
$conn = new SQLite3(':memory:');
$conn->exec("CREATE TABLE test (id INTEGER)");
// Print "Query executed" to the output
echo "Query executed";
$conn->close();
// Print " -- connection closed" to the output
echo " -- connection closed";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not checking $mysqli->connect_error after connecting, so a failed connection is ignored and later queries fail with confusing errors.
  2. Using the old mysql_* functions, which were removed in PHP 7 and no longer exist.
  3. Hard-coding database credentials in the script that is served publicly instead of keeping them in a protected config file.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.