PHP MySQL Connect
In this page:
$conn = mysqli_connect($host, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_close($conn);
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.
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.
Example: Checking for Connection Errors
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
// Check whether `!$db`
if (!$db) {
// Print "Connection failed" to the output
echo "Connection failed";
// Otherwise, run this branch
} else {
// Print "Connected successfully -- check mysqli_connect_error() on a real server" to the output
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.
Example: Closing a Database Connection
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
// Print "Connected" to the output
echo "Connected";
$db->close();
// Print " -- closed" to the output
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.
Example: Storing Credentials Securely
<?php
// Declare `$host`, set to `getenv('DB_HOST') ?: 'localhost'`
$host = getenv('DB_HOST') ?: 'localhost';
// Declare `$password`, set to `getenv('DB_PASSWORD') ?: ''`
$password = getenv('DB_PASSWORD') ?: '';
// Print "Using credentials from environment, not hardcoded in the script" to the output
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.
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