how connect to database in php code example

Example 1: php connect to mysql

$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";


Simplified

$conn = mysqli_connect('localhost', 'username', 'password');
$database = mysqli_select_db($conn, 'database');

Example 2: database connectivity in php

<?php
///////////neha jaiswal/////
/////set variable/////////
$serve="localhost";
$user="root";
$password="";
$db="cart_system";///database name
///create connection with db////
$conn=mysqli_connect($serve,$user,$password,$db);
////check condition for connection fail or not
 if ($conn) {
 echo "connection success"; 
 }else
{echo "connection unsuccess"; 
 }
  ?>

Example 3: mysql db connection in php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn= mysqli_connect($servername,$username,$password,$dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
echo "Connected Successfully.";
?>

Tags:

Php Example