Create Connection
The first step when start working with the local or online server is to check the connection or communication with the server . For this we need four variables to store four parameters which are used to connect with the local server .
$servername = "localhost";
$username = "username";
$password = "password";
$database = "mydb"
$servername specifies the server to which we are communicating .
$username is the user which is allowed or which is alloted to access the database . ( Allocation of user with the authentication is done by system administrator and always done manually by loggin in to the system c panel )
$password is the password for the user which we set at the time of creation of a user from c panel
$database holds the name of the database to the which the user is alloted .
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
All the three codes will be executed from a web page .