PHP MySQL Connect
In this page:
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
// mysqli_connect($host, $username, $password, $database) on a real server
$db = new SQLite3(':memory:');
echo "Connected and database selected";
?>
Login to try C/C++/Java/PHP code in the editor
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
$db = new SQLite3(':memory:');
if (!$db) {
echo "Connection failed";
} else {
echo "Connected successfully -- check mysqli_connect_error() on a real server";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$db = new SQLite3(':memory:');
echo "Connected";
$db->close();
echo " -- closed";
?>
Login to try C/C++/Java/PHP code in the editor
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
$host = getenv('DB_HOST') ?: 'localhost';
$password = getenv('DB_PASSWORD') ?: '';
echo "Using credentials from environment, not hardcoded in the script";
?>
Login to try C/C++/Java/PHP code in the editor
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
// mysqli_connect($host, $user, $pass, $db, 3307) -- custom port example
echo "A non-default port can be passed as an extra argument";
?>
Login to try C/C++/Java/PHP code in the editor
- 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.
- 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.
- Leaving a database connection open for the entire duration of a long-running script when it is only needed briefly at the start.
- 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.
mysqli has been PHP's recommended MySQL extension since PHP 5.5, when the older, unsafe mysql_* functions were removed.
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- PHP MySQL Introduction
- PHP MySQLi Connection
- PHP PDO Introduction
- PHP CRUD Operations
- PHP Prepared Statements
- PHP Stored Procedures
- PHP Transactions
- PHP Error Handling in DB
- PHP MySQL Connect
- PHP MySQL Create DB
- PHP MySQL Create Table
- PHP MySQL Insert Data
- PHP MySQL Get Last ID
- PHP MySQL Insert Multiple
- PHP MySQL Prepared Statements
- PHP MySQL Select Data
- PHP MySQL Where
- PHP MySQL Order By
- PHP MySQL Delete Data
- PHP MySQL Update Data
- PHP MySQL Limit Data