Mysqli_connect Function:
MySQLi connection using PHP gives the mysqli_connect() function to connect a database. This function takes six parameters and returns a boolean value.
Syntax:
mysqli_connect(host, username, password, dbname, port, socket)
Host | Optional/Specifies a host name or an IP address |
Username | Optional/Specifies the MySQL username |
Password | Optional/Specifies the MySQL password |
DbName | Optional/Specifies the default database to be used |
Port | Optional/Specifies the port number to attempt to connect to the MySQL server |
Socket | Optional/Specifies the socket or named pipe to be used |
Example:
<?php
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
?>
Object Oriented style
Create object of MySQLi class and use it to get the connection
Syntax
$mysqli = new mysqli(host, username, password, dbname, port, socket)
Example:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli ->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli ->connect_error;
exit();
}
?>