Connecting to the database server.
First, you have to make sure that the database is created on the server, and that will be used as the database name.
After creating the database with the server name, user name, and password known, a connection to the server to access the database can be established.
<?php
// Define the names to the host, username, password and database name
$host = "localhost"; // Host
$userName = "root"; // Username
$passWord = "your_password";
$dbName = "my_database";
?>
To establish a connection to the server, the function mysqli_connect() is used and accepts parameters including hostname, user name, password, and database name.
$connection = mysqli_connect($host, $userName, $password, $dbName);
The "new mysqli()" can also be used to establish the connection in the same way as the "mysqli_connect()."
$connection = new mysqli($host, $userName, $password, $dbName);
Checking if the connection is established
This can be achieved using an "if control statement" to check and display a "connection success message" if the connection is established or a "connection failure message" if a connection is not established.
if ($connection){
// Success message
echo "Connected successfully";
}else{
// Failure message
echo "Connection failure";
}
Conclusion
I hope you have learned a lot about how to connect to the server and access the database. If there is anything you feel I have not covered very well, kindly leave a comment or connect with me so that we can find a solution to that.
Thank you for reading, and we can connect via my platforms.
Twitter
Facebook
Instagram
Github
LinkedIn
Subscribe to my newsletter
Read articles from AKANYIJUKA DANSON directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
AKANYIJUKA DANSON
AKANYIJUKA DANSON
A Software Developer in both Web and Mobile, It consultant that produces results in time and passionate about tech. Bachelor's Degree in Information Technology and Computing Kyambogo University