Connect MySQL database On PHP website

Many dynamic website are created by PHP with MySQL. So this post helps for the beginners to connect the database with PHP. You must establish the connection to get, post, update or delete data from the database.

There are two ways to connect the MySQL database with PHP.

  • MySQLi
  • PHP Data Object (PDO)

 Let's see the codes below,

MySQLi

Syntax: mysql_connect(hostname, username, password, dtabasename);

<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'dbname');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

 

PHP Data Object (PDO)

Syntax: new PDO("mysql:host=hostname;dbname="dtabasename,username, password);

<?php 
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','dbname');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS);
echo "Connected successfully.";
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?>

 

About author
George
George
PHP Developer
0 comments
Be a First Comment
Add Your Comment