The mysqli_connect()
function in PHP is used to open a new connection to a MySQL database server. It is part of the MySQLi (MySQL Improved) extension and supports both procedural and object-oriented programming.
Syntax
mysqli_connect(host, username, password, dbname, port, socket);
Parameters
Parameter |
Description |
host |
Hostname or IP address of the MySQL server (e.g., “localhost”, “127.0.0.1”) |
username |
MySQL username |
password |
MySQL password |
dbname |
(Optional) Name of the database to connect to |
port |
(Optional) Port number (default: 3306) |
socket |
(Optional) Socket or named pipe |
Basic Example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
With Port and Database
<?php
$conn = mysqli_connect("localhost", "root", "mypassword", "my_database", 3306);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected to database with port!";
?>
Handling Connection Error
<?php
$conn = mysqli_connect("localhost", "wrong_user", "wrong_pass");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
?>
Closing the Connection
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
if ($conn) {
mysqli_close($conn);
}
?>
Notes:
- It’s best practice to check for errors after trying to connect.
- Use prepared statements with
mysqli
or switch to PDO for more secure and flexible database interactions.