db connection in php code example
Example 1: php sql connection
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn= mysqli_connect($servername,$username,$password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected Successfully.";
?>
Example 2: php connect to mysql
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
Simplified
$conn = mysqli_connect('localhost', 'username', 'password');
$database = mysqli_select_db($conn, 'database');
Example 3: db connection in php
Just include this Temlate in other file using PHP Include/Require Keywords
And Make Connection In One Shot :)
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test";
$con = mysqLi_connect($server, $username, $password, $database);
if(!$con){
die ("Connection Terminated! by Die() function". mysqLi_connect_error());
}
else {
echo "Connection Succefully Happened! <br>";
}
?>
Example 4: how to connect to a database in php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example 5: test mysql connection
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>