PHP PDO
PHP PDO (PHP Data Objects) is a lightweight, consistent interface for accessing databases in PHP. PDO provides a data-access abstraction layer, which means that, regardless of which database we are working on, we must use the same PDO functions to work with databases.
Syntax
$pdo = new PDO('mysql:host=hostname;dbname=database_name', $username, $password);
Example
// Establishing the connection
$pdo = new PDO('mysql:host=localhost;dbname=test', $username, $password);
// Creating a query
$sql = "SELECT * FROM users";
// Executing the query
$result = $pdo->query($sql);
// Fetching the result set
foreach($result as $row) {
echo $row['name'] . "\n";
}
// Closing the connection
$pdo = null;
Output
John
Samuel
Peter
Explanation
- To work with PDO, we first need to establish a connection to the database by creating an instance of the PDO class.
- We pass the database connection details as arguments to the PDO constructor, which include the hostname, database name, username, and password.
- After establishing the connection, we can create a SQL query and execute it using the
query()
method of the PDO class. This method returns a result set that we can fetch using a loop. - Finally, we close the connection by setting the
$pdo
variable tonull
.
Use
PDO is used to work with different types of databases such as MySQL, PostgreSQL, Oracle, and more. It provides a simple and consistent way of working with these databases, which makes it easier to write database-related code in PHP.
Important Points
- PDO provides a consistent interface for working with different databases in PHP.
- PDO is a lightweight library that does not require any additional installation or configuration.
- PDO supports prepared statements, which help to prevent SQL injection attacks.
- PDO supports transactions, which help to ensure data consistency in the database.
Summary
PHP PDO provides a consistent interface for working with different types of databases in PHP. It is a lightweight library that simplifies database-related code and provides features such as prepared statements and transactions to help ensure data consistency and prevent security vulnerabilities.