Skip to content

Instantly share code, notes, and snippets.

@azazqadir
Created May 14, 2018 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azazqadir/46747dd0d177886b91b6b47f15071f24 to your computer and use it in GitHub Desktop.
Save azazqadir/46747dd0d177886b91b6b47f15071f24 to your computer and use it in GitHub Desktop.
Creating a Connection Between MySQL and PHP

This tutorial guides you how to connect MySQL database with PHP. To establish the connection, you can simply do it with MySQL or you can use MySQLi or PDO (PHP Data Objects).

For MySQL, simply add followin code in db_connection.php file in your root.

<?php

function OpenCon()
 {
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "1234";
 $db = "example";


 $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);

 
 return $conn;
 }
 
function CloseCon($conn)
 {
 $conn -> close();
 }
   
?>

For MySQLi, add following code

<?php

$servername = "localhost";

$username = "username";

$password = "password";

$db = "dbname";



// Create connection

$conn = mysqli_connect($servername, $username, $password,$db);



// Check connection

if (!$conn) {

   die("Connection failed: " . mysqli_connect_error());

}

echo "Connected successfully";

?>

For PDO, add following code

<?php

$servername = "localhost";

$username = "username";

$password = "password";

$db = "dbname";



try {

   $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password, $db);

   // 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();

   }

?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment