php db connection code example

Example 1: php sql connection

<?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.";
?>

Example 2: 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 3: 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 4: $conn php

<?php
    $user = "username";
    $pass = "password";
    $host = "host";
    $dbdb = "database";
    
$conn = new mysqli($host, $user, $pass, $dbdb);
   if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
?>

Example 5: db connection in php

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


    ?>

Example 6: mysqli connect

<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

// Check connection
if ($mysqli -> connect_errno) {

  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  
  exit();

  }
?>

Tags:

Sql Example