Hi Guys, today we are going to study about how to create MySQL database connection. There are various ways, one of them we are going to discuss here;
Using mysqli Class:
Create object of mysqli class, and pass the argument in the constructor as Host name, user name and password.
new mysqli(hostname, userName, password);
Here is the example code to connect with Database on a server localhost. if there is error during connection the it will go to the if block and die and print a message like connection failed with the error cause. otherwise it will print connected successfully.
<?php $userName = "username"; $password ="password"; $hostname = "localhost"; //create connection $conn = new mysqli($hostname, $userName, $password); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
Output: