In this article, we will discuss PDO in PHP in detail.
There are three main options forĀ
PHP
<?php
try {
$dbhost = 'localhost';
$dbname='gfg';
$dbuser = 'root';
$dbpass = '';
$connect = new PDO(
"mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
$count = $connect->exec("DELETE FROM employee WHERE emp_id = 123 ");
echo("Number of rows to be deleted from the employee table is: ". $count);
?>
ting to a MySQL database server.
MySQLi procedural and MySQLi object-oriented only support MySQL database but PDO is an advanced method along with MySQL which supports Postgres, SQLite, Oracle, and MS SQL Server.
PDO is more secure than the first two options and it is also faster in comparison with MySQLi procedural and MySQLi object-oriented.
PDO is a database access layer that provides a fast and consistent interface for accessing and managing databases in PHP applications. Every DBMS has a specific PDO driver that must be installed when you are using PDO in PHP applications.
It simplifies the database operations including:
- Creating database connection
- Executing queries
- Handling errors
- Closing the database connections
When we want to connect PHP and MySQL then we need to follow 3 steps:
- Connection with the database
- Run SQL Query
- Closing the database connection
Steps for connection using PDO.
Connection:
In this step, we connect with the database
$conn = new PDO($db_name,$username,$password);
When we want the connection between PHP and MySQL using PDO then we need to create an object of the PDO class.
$db_name = "mysql:host=localhost;dbname:gfg";
Note: $db_name contains the following information.
Run SQL query: To run SQL query we can use two methods:
$sql = $conn->query("select * from students");
$sql = $conn->prepare("select * from students");
Note: The prepare() method is more secure than the query() method.
Close the connection:
For closing the database connection using PDO.
$conn = null;
Parameters: It contains the following parameters.
- dsn: It contains the information regarding connection to the database.
- user: It contains the user name.
- password: It contains the password of the database.
Return Value:
On success, it will return the PDO object. And on failure, it will return the PDOException object.
Handling error during connection:
The PDOException object will be thrown in case of any error. We can catch the exception to handle the error.Ā
PHP
<?php
try {
$dsn = "mysql:host=localhost;dbname=gfg";
$user = "root";
$passwd = "";
$pdo = new PDO($dsn, $user, $passwd);
}
catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Output:
Error : SQLSTATE[28000] [1045]
Access denied for user 'roott'@'localhost'
(using password: NO)
Example 1: Suppose we have a database "gfg" with a table "students". We want to fetch the details like "id" and name of all the students present in the table "students".
PHP
<?php
$dsn = "mysql:host=localhost;dbname=gfg";
$user = "root";
$passwd = "";
$pdo = new PDO($dsn, $user, $passwd);
$stm = $pdo->query("SELECT * FROM students");
$rows = $stm->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
printf("{$row['id']} {$row['name']}\n");
}
?>
Output:
1 Student1
2 Student2
3 Student3
4 Student4
Example 2: In this case, suppose we have the "employee" table in "gfg" database. We want to delete the employee from the "employee" table whose "id = 123".Ā
PHP
<?php
try {
$dbhost = 'localhost';
$dbname='gfg';
$dbuser = 'root';
$dbpass = '';
$connect = new PDO(
"mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
$count = $connect->exec("DELETE FROM employee WHERE emp_id = 123 ");
echo("Number of rows to be deleted from the employee table is: ". $count);
?>
Output:
The number of rows to be deleted from the employee table is: 1
Benefits of PDO:
- Usability: PDO contains helper functions to operate automatic routine operations.
- Reusability: We can access multiple databases because it offers a unified API.
- Security: It provides protection from SQL injection because it uses a prepared statement. A prepared statement separates the instruction of the SQL statement from the data.
- Error handling: It uses exceptions for error handling. There are three types of modes:
- Multiple database support: It is used to access any database which is written for the PDP driver. We need to find a suitable driver and add them when we use them. There are several PDO drivers available like Microsoft SQL Server, Sybase, PostgreSQL, and many more.
Supported Database: PDO supports 12 different databases.
- MySQL
- PostgreSQL
- Oracle
- Firebird
- MS SQL Server
- Sybase
- Informix
- IBM
- FreeTDS
- SQLite
- Cubrid
- 4D
Similar Reads
What is stdClass in PHP?
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified. But, if object type is converted/type-casted an instance of stdClass
3 min read
What is the use of $GLOBALS in PHP ?
In this article, we will discuss $GLOBALS in PHP. $GLOBALS is a superglobal variable used to access global variables from anywhere in the PHP program. PHP stores all global variables in an array called $GLOBALS[index]. Syntax: $GLOBALS['index']=value;value is the input value.The index is the unique
1 min read
What is PHP and Why we use it ?
What is PHP? PHP(short for Hypertext PreProcessor) is the most widely used open source and general purpose server side scripting language used mainly in web development to create dynamic websites and applications. It was developed in 1994 by Rasmus Lerdorf. A survey by W3Tech shows that almost 79% o
2 min read
What is the purpose of php.ini file ?
In this article, we will learn about the purpose of the php.ini file. At the time of PHP installation, php.ini was a special file provided as a default configuration file.Purpose of php.ini file:Itâs a very essential configuration file that controls what a user can or cannot do with the website.Each
5 min read
PHP | ob_start() Function
Let's take a quick recap. PHP is an interpreted language thus each statement is executed one after another, therefore PHP tends to send HTML to browsers in chunks thus reducing performance. Using output buffering the generated HTML gets stored in a buffer or a string variable and is sent to the buff
2 min read
When do we need Interfaces in PHP?
Interface are definitions of the public APIs that classes (implementing an interface) must implement. It is also known as contracts as an interface allows to specify a list of methods that a class must implement. Interface definition is similar to the class definition, just by changing the keyword c
3 min read
What is autoloading classes in PHP ?
In order to use a class defined in another PHP script, we can incorporate it with include or require statements. However, PHP's autoloading feature does not need such explicit inclusion. Instead, when a class is used (for declaring its object etc.) PHP parser loads it automatically, if it is registe
2 min read
$this keyword in PHP
$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods. Example 1: A simple
3 min read
Introduction to PHP8
Back in the mid-1990s, PHP started as a Personal Home Page, but now it's known as Hypertext Preprocessor. It's a widely used scripting language that is perfect for web development and can easily be inserted into HTML. Over time, PHP has become super powerful for making dynamic and engaging web apps.
5 min read
PHP Pagination | Set 2
In the previous article on PHP Pagination, we had seen why pagination is needed and also developed a basic structure for implementing a pagination system using PHP. In continuation, let us start with our development process and first create a script to connect to our Database. Connecting to Database
7 min read