PHP mysqli_connect(): Connect to MySQL or MariaDB
mysqli_connect() opens a MySQL or MariaDB connection and returns a mysqli object on success. Start with a running server, a database, and an account that can access it. The example keeps configuration outside the public directory, sets utf8mb4, and checks the connection with a read-only query.
Prepare the connection details and arguments
Verify that PHP has loaded mysqli, the MySQL Improved extension. php -m checks the command-line runtime. Check the PHP that handles web requests separately if your site uses different settings. Grant the database account only the privileges the application needs. PHP Manual — Installing mysqli
| Argument | Meaning | What to check |
|---|---|---|
| hostname | Hostname or IP address | Choose the intended TCP address or local socket. |
| username | Database account | Confirm it is allowed from this client host. |
| password | Account password | Keep it out of public code and responses. |
| database | Default database | It must exist and be accessible to the account. |
| port | TCP port | 3306 is common. Check the configured port. |
| socket | Socket or named pipe | Its use depends on the host and platform. |
The table lists the arguments in call order. The example assumes PHP and the database server are on the same computer and uses TCP. For a remote database, check which client sources the server accepts and use the deployment’s TLS configuration with certificate verification. PHP Manual — mysqli_connect()
Keep configuration private and connect
Create database-config.php and public/connect.php in a practice directory. Set the document root to public. Save the following array in the first file. Replace the example account, database, and password placeholder with your own settings.
<?php
return [
'host' => '127.0.0.1',
'username' => 'learning_user',
'password' => 'REPLACE_WITH_YOUR_PRIVATE_PASSWORD',
'database' => 'learning',
'port' => 3306,
];
Restrict the configuration file to the PHP process and other authorized readers. Exclude it from version control and public deployment. If your service already uses environment variables or a secret manager, you can supply configuration that way. This example looks one directory above public.
<?php
header('Content-Type: text/plain; charset=UTF-8');
if (!extension_loaded('mysqli')) {
http_response_code(500);
exit('The mysqli extension is required.');
}
$configPath = dirname(__DIR__) . '/database-config.php';
if (!is_file($configPath)) {
http_response_code(500);
exit('The database configuration file cannot be read.');
}
$config = require $configPath;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = null;
try {
$link = mysqli_connect(
$config['host'],
$config['username'],
$config['password'],
$config['database'],
$config['port']
);
mysqli_set_charset($link, 'utf8mb4');
$result = mysqli_query($link, "SELECT 'Connection verified' AS message");
$row = mysqli_fetch_assoc($result);
echo $row['message'], PHP_EOL;
echo 'charset: ', mysqli_character_set_name($link), PHP_EOL;
mysqli_free_result($result);
} catch (mysqli_sql_exception $e) {
http_response_code(500);
error_log('Database check failed. Error code: ' . $e->getCode());
echo 'The database connection or query failed.', PHP_EOL;
} finally {
if ($link instanceof mysqli) {
mysqli_close($link);
}
}
Run php -S 127.0.0.1:8000 -t public from the practice directory. Open http://127.0.0.1:8000/connect.php. On success, you should see a confirmation and charset: utf8mb4. This SELECT reads a literal string without using a table. php public/connect.php shows the message in the terminal, while a web request also lets you check the HTTP status. Stop the local server with Ctrl+C.
Set the connection charset and error mode
Setting mysqli_report() explicitly lets the same catch block handle mysqli_sql_exception from connecting, setting the charset, or running the query. PHP 8.1 and later use this mode by default, so an exception may occur before an old $link === false check. The example returns a generic response and logs the numeric error code privately. PHP Manual — mysqli_report()
mysqli_set_charset() controls the character set used by the connection. Check the database storage charset and HTTP response encoding separately. The example releases the result and closes the open connection in finally. If a later query uses form input, bind values to a prepared statement. PHP Manual — mysqli_set_charset() PHP Manual — Prepared statements
Diagnose connection failures in order
| Symptom | What to check |
|---|---|
| Undefined mysqli function | Check whether the current PHP runtime loads mysqli. |
| Connection refused or timed out | Check server status, the address and port, and network access rules. |
| Access denied | Check credentials and the client host as recognized by the server. |
| Unknown database | Check the database name and that the account can access it. |
| Socket error | Check the socket path or use the intended TCP address. |
| Broken characters or emoji | Check the connection, response, and storage character sets separately. |
On Unix-like systems, localhost usually selects a local socket. Use 127.0.0.1 and an explicit port to connect over TCP on the same host. Windows can use different transports. PHP Manual — Connections
To check the failure path, temporarily set an unused port in your local exercise and look for HTTP 500 with the generic response, then restore the original port. Consult the restricted server log for the error code. Keep display_errors off in production and remove the diagnostic file when finished.




