The mysqli_connect() function in PHP is used to connect you to the database. In the previous version of the connection, the mysql_connect() was used for connection and then there comes mysqli_connect() function where i denotes an improved version of the connection and is more secure than mysql_connect().
Syntax:
mysqli_connect ( "host", "username", "password", "database_name" );
Parameters Used:
- host: It is optional and it specifies the hostname or IP address. In the case of local server, localhost is used as a general keyword to connect the local server and run the program.
- username: It is optional and it specifies MySQL username. In the local server username is root.
- Password: It is optional and it specifies MySQL password.
- database_name: It is a database name where operations perform on data. It is also optional.
Return Value:
- It returns an object which represents the MySql connection. If the connection failed then it returns FALSE.
Program: Below is the implementation of mysqli_connect() function.
php
<?php
mysqli_connect("localhost", "root", "", "GFG");
if (mysqli_connect_error()) {
echo "Connection Error.";
} else {
echo "Database Connection Successfully.";
}
?>
|
Output:
Database Connection Successfully.
We can also use the die() method to terminate the program with a message if the connection fails.
Program: Below is the implementation of the die() method with the mysqli_connect() method.
PHP
<?php
mysqli_connect("localhost", "root", "", "GFG") or
die("Connection Unsuccessfull");
echo "Connection Successfull";
?>
|
Output:
Database Connection Successfully.
Unlock the Power of Placement Preparation!
Feeling lost in OS, DBMS, CN, SQL, and DSA chaos? Our
Complete Interview Preparation Course is the ultimate guide to conquer placements. Trusted by over 100,000+ geeks, this course is your roadmap to interview triumph.
Ready to dive in? Explore our Free Demo Content and join our
Complete Interview Preparation course.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
24 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...