PHP Connect
Syntax
The mysqli_connect()
function is used to open a new connection to the MySQL server.
mysqli_connect(servername, username, password, dbname);
Example
$servername = "localhost";
$username = "root";
$password = "my_password";
$dbname = "my_database";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
Output
Connected successfully
Explanation
The mysqli_connect()
function takes four arguments:
servername
- the name of the server hosting the MySQL databaseusername
- the username used to connect to the MySQL databasepassword
- the password used to connect to the MySQL databasedbname
- the name of the database you want to connect to
When a connection is successfully established, the mysqli_connect()
function returns a new mysqli
object that can be used to execute SQL queries.
In the above example, we create a new connection to the MySQL server using the provided servername
, username
, password
, and dbname
. We then check if the connection was successful and display a message accordingly.
Use
The mysqli_connect()
function is used to connect PHP applications to a MySQL database. Once a connection is established, various SQL queries can be executed to insert, update, delete or retrieve data from the database.
Important Points
- The
mysqli
extension must be enabled in order to use themysqli_connect()
function. - Always check if a connection was successful before attempting to run SQL queries.
- Close the connection to the MySQL server after executing all necessary queries using the
mysqli_close()
function.
Summary
The mysqli_connect()
function is used to establish a new connection to a MySQL database. It takes four arguments: servername
, username
, password
, and dbname
. Once a connection is established, SQL queries can be executed using a mysqli
object. When done, the connection should be closed using the mysqli_close()
function.