Menu Close

Connect MySQL database On PHP website

0
(0)

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());
}
?> 

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Share

Posted in MySQL, PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

You can also read...