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

PHP MySQL Connect

Before a PHP script can run any query against a MySQL database, it first has to establish a connection -- telling MySQL which server to talk to, and authenticating with a username and password. mysqli_connect() (or the object-oriented new mysqli(...)) is the standard way to open that connection.

Establishing a Basic Connection

mysqli_connect($host, $username, $password, $database) opens a connection to a MySQL server using the given credentials and immediately selects the named database, returning a connection object you will pass to every query function afterward.

Note: Use "localhost" as the host when your PHP script and MySQL server run on the same machine, which is the most common local development setup.

Warning: A wrong username, password, or host produces a connection failure that must be checked explicitly -- mysqli_connect() does not throw an exception by default.

Example: Establishing a Basic Connection

php
<?php
// mysqli_connect($host, $username, $password, $database) on a real server
$db = new SQLite3(':memory:');
echo "Connected and database selected";
?>

Checking for Connection Errors

mysqli_connect_error() returns a description of what went wrong if the most recent connection attempt failed -- checking this immediately after connecting lets you fail fast with a clear message instead of continuing with a broken, unusable connection.

Note: Show a clear error message during development, but avoid displaying raw database error details to end users in production, since they can reveal sensitive infrastructure information.

Warning: Continuing to run queries after a failed connection produces a confusing cascade of unrelated errors -- always stop and handle the connection failure immediately.

Example: Checking for Connection Errors

php
<?php
$db = new SQLite3(':memory:');
if (!$db) {
    echo "Connection failed";
} else {
    echo "Connected successfully -- check mysqli_connect_error() on a real server";
}
?>

Closing a Database Connection

mysqli_close($conn) (or $conn->close() in OOP style) explicitly closes a database connection once it is no longer needed, freeing up the resource on the MySQL server -- though PHP also closes any open connections automatically once a script finishes running.

Note: Explicitly closing a connection is most valuable in long-running scripts (like CLI tools or workers) where a connection might otherwise stay open far longer than necessary.

Warning: Attempting to run a query after a connection has been closed produces an error -- make sure all database work finishes before closing.

Example: Closing a Database Connection

php
<?php
$db = new SQLite3(':memory:');
echo "Connected";
$db->close();
echo " -- closed";
?>

Storing Credentials Securely

Database credentials should never be hardcoded directly into a script that gets committed to version control -- loading them from environment variables, or from a separate config file excluded from git via .gitignore, keeps sensitive values out of your codebase's history entirely.

Note: Use a .env file (loaded with a library like vlucas/phpdotenv) or your hosting platform's environment variable settings to keep credentials outside your committed code.

Warning: Credentials committed to version control remain in that history forever, even if removed in a later commit -- treat any accidentally-committed credential as compromised and rotate it.

Example: Storing Credentials Securely

php
<?php
$host = getenv('DB_HOST') ?: 'localhost';
$password = getenv('DB_PASSWORD') ?: '';
echo "Using credentials from environment, not hardcoded in the script";
?>

Connecting with a Custom Port or Options

mysqli_connect() accepts optional port and socket parameters beyond the basic four, useful when MySQL is not running on the default port 3306, such as in certain Docker or shared-hosting setups where a non-standard port is required.

Note: When connecting to a MySQL instance behind a proxy or in a containerized environment, double-check whether a non-default port needs to be passed explicitly.

Warning: Omitting a required custom port when the server is not listening on the default 3306 produces a connection failure that can look identical to a wrong-credentials error.

Example: Connecting with a Custom Port or Options

php
<?php
// mysqli_connect($host, $user, $pass, $db, 3307) -- custom port example
echo "A non-default port can be passed as an extra argument";
?>
Common Mistakes
  1. Hardcoding database credentials directly in a script that gets committed to version control, instead of loading them from an environment variable or a config file kept out of the repository.
  2. Forgetting to check whether the connection actually succeeded before running queries against it, leading to a confusing cascade of errors on every subsequent database call.
  3. Leaving a database connection open for the entire duration of a long-running script when it is only needed briefly at the start.
Chapter Summary
  • mysqli_connect($host, $user, $password, $database) opens a connection and returns a connection object, or false on failure.
  • Always check the connection for errors immediately after attempting it, before running any queries.
  • Database credentials should be stored outside the main codebase (environment variables or a gitignored config file), never hardcoded in committed source.
Browser Support

mysqli has been PHP's recommended MySQL extension since PHP 5.5, when the older, unsafe mysql_* functions were removed.

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.