PHP Database Connection

Database connection is very important component in web development to allow us for store data and fetch data from database. PHP uses multiple techniques to connect PHP to database. In this article, we will learn about database & also PHP database connection with help of examples.

What is Database?

A collection of different units of information is referred to as data. This “data” can take many forms, including text, numbers, media, and so on.
The database is a structured collection of data that is arranged to make it easy to access, maintain, and update. In simple terms, a database is a location where information is stored.
In terms of website, we make multiple forms in a website or webpage like contact us form, Sign in form, Registration form, and many more. When we want to store these forms data for future use, we store these data in Database.
For database connection with PHP, we mostly used MySQL to store, display, add, modify records.

For connect PHP with MySQL, we used some local servers as follows:

Local ServerSupported Operating System
XAMPP (mostly used)Support Windows, Linux
WAMP (Windows Apache MySQL PHP)Support only For Windows
LAMP (Linux Apache MySQL PHP)Support only For Linux
MAMP (Mac Apache MySQL PHP)Support only For Mac users

You can also check this on YouTube

There are three types of methods in PHP to connect MySQL database:

  • MySQL: Due to security considerations such as SQL injection, this strategy is becoming obsolete.
  • MySQLi: It is Improved version of MySQL and object-oriented. It also support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.
  • PDO: It stands for PHP Data Objects (PDO) and PDO extension is a Database Abstraction Layer. The major advantage of using PDO is that your code stays simple and portable.

Also read Export Data to CSV

How to Connect With MySQL?

It is old techniques in lower version of PHP. With below code, connection will made successfully, but it will show Deprecated warning.

<?php
$host = "localhost";
$username = "root";
$password = "";
$connection = mysql_connect($host, $username, $password);
if (!$connection) 
{
	die('Connection failed: ' . mysql_error());
}
else
{
	echo "Database Connected successfully";
}

?>

How to connect with MySQLi?

<?php
$servername = "localhost";
$username = "root";
$password = "";

$conn = new mysqli($servername, $username, $password);

if ($conn->connect_error) 
{
     die("Connection failed: " . $conn->connect_error);
}
else
{
      echo "Database Connected successfully";
}
?>

Now, we have $conn, the database connection object. We can use this object for all the communication to the database.

<?php
// selecting database "test1"
mysqli_select_db($conn,"test1");
?>

You can also pass the database as an argument at the time of connection establishment.

<?php
$conn = new mysqli($servername, $username, $password, $databaseName);
?>

How to connect with PDO(PHP Data Object)?

<?php
$servername = "localhost";
$username = "root";
$password = "";

try 
{
	
	$conn = new PDO("mysql:host=$servername;dbname=test1", $username, $password);
	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

	echo "Connected successfully";
}
catch(PDOException $e)
{

	echo "Connection failed: " . $e->getMessage();
}
?>

PDO Features

Exception Handling

PDO always uses try-catch blocks to handle errors which comes during database connection.

Prepared Statement

Prepared statements are safe because of its security reasons. It always protect us from preventing SQL injection attacks. PDO support prepared statements.

For dynamic PHP applications, making a database connection is a crucial first step. You may connect to your MySQL database quickly and securely with MySQLi or PDO. With MySQLi giving functionality exclusive to MySQL and PDO offering a versatile, multi-database interface, each approach has advantages of its own. You may build reliable and safe PHP apps by adhering to recommended practices, which include using configuration files and gracefully resolving failures.

Categorized in: