PHP MySQL mysqli_connect() function
In PHP, the mysqli_connect()
function is used to establish a connection to a MySQL database using the MySQLi extension in a procedural style. Here's a breakdown of how it works:
Syntax
mysqli_connect('localhost', 'username', 'password', 'database');
Parameters
host: The hostname of the MySQL server. For a local server, you can use
'localhost'
. If you're connecting to a remote server, use the IP address or domain name of that server.username: The MySQL username you want to connect with. This user must have the appropriate permissions to access the specified database.
password: The password associated with the MySQL username.
database: The name of the database you want to select after connecting. This parameter is optional; if not provided, you need to select the database using
mysqli_select_db()
later.port: The port number to use for the connection. The default MySQL port is
3306
. This parameter is optional.socket: The socket or named pipe to use for the connection. This parameter is optional.
Example
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
Error Handling
If the connection fails, mysqli_connect()
returns false
. You can use mysqli_connect_error()
to retrieve a string description of the last connection error.
Closing the Connection
It's a good practice to close the connection once you're done with it using mysqli_close()
:
mysqli_close($conn);
Notes
- MySQLi (MySQL Improved) is an extension that provides an improved interface for accessing MySQL databases compared to the old
mysql
extension. - Procedural vs. Object-Oriented: MySQLi can be used in both procedural and object-oriented styles. The example provided uses the procedural style.