connect php to mysql 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: mysql connect php

# MySql improved
<?php
    $mysqli = new mysqli("localhost", "username", "password", "dbname");
	$result = $mysqli->query("SELECT lastname FROM employees");
?>
# Connection with PDO
<?php
    $myPDO = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');
	$result = $myPDO->query("SELECT lastname FROM employees");
?>
# With PHP legacy functions:
<?php
    mysql_connect('localhost','username','password');
    mysql_select_db("dbname");
	$result = mysql_query('SELECT lastname FROM employees');
?>

Example 4: connect php to mysql pdo

<?php 
  
	$pdo = new PDO('mysql:host=localhost;
  				dbname=the_name_of_your_databe,
  				'username', 
                'password'');
# by default your username is root 
# if you don't have a password don't fill in it

#(optional) : 
	$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

?>

Example 5: php mysql connect

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

Example 6: 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"; 
 }
  ?>

Tags:

Php Example