PHP MySQLi Connection
In this page:
$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
// 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";
?>
Login to try C/C++/Java/PHP code in the editor
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
// Object-oriented style: $conn = new mysqli($host, $user, $password, $database);
$conn = new SQLite3(':memory:');
echo get_class($conn);
?>
Login to try C/C++/Java/PHP code in the editor
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
// 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";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
// 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)";
?>
Login to try C/C++/Java/PHP code in the editor
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
// 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";
?>
Login to try C/C++/Java/PHP code in the editor
- Not checking
$mysqli->connect_errorafter connecting, so a failed connection is ignored and later queries fail with confusing errors. - Using the old
mysql_*functions, which were removed in PHP 7 and no longer exist. - Hard-coding database credentials in the script that is served publicly instead of keeping them in a protected config file.
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