N
$host = "localhost";//Ip of database, in this case my host machine
$user = "root"; //Username to use
$pass = "qwerty";//Password for that user
$dbname = "DB";//Name of the database
try {
$connection = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo $e->getMessage();
}
N
<?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();
}
?>
N
Just include this Temlate in other file using PHP Include/Require Keywords
And Make Connection In One Shot :)
<?php
// echo "Welcome to Connecting of DB Tutorial!";
// echo "<br>";
// 1. PDO - Php Data Objects
// 2. MySQLi extension
// Set Connection Variable
$server = "localhost";
$username = "root";
$password = "";
$database = "test";
// Create A Connection
$con = mysqLi_connect($server, $username, $password, $database);
// Check For Connection
if(!$con){
die ("Connection Terminated! by Die() function". mysqLi_connect_error());
}
else {
echo "Connection Succefully Happened! <br>";
}
?>
N
<?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();
}
?>