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

PHP MySQLi Connection

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
$conn = new SQLite3(':memory:');
if (!$conn) {
    echo "Connection failed";
} else {
    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
$host = getenv('DB_HOST') ?: 'localhost';
$user = getenv('DB_USER') ?: 'root';
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
$conn = new SQLite3(':memory:');
$conn->exec("CREATE TABLE test (id INTEGER)");
echo "Query executed";
$conn->close();
echo " -- connection closed";
?>

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.