Page 522 - Computer_Science_F5
P. 522
Case 2: Connecting PHP to MySQL using PDO
Using PDO (PHP Data Objects) for database interactions in PHP applications
provides a uniform method to access databases. PDO supports multiple database
systems like MySQL, PostgreSQL, SQLite, etc., making it a flexible choice for
developers. It also offers a simple and consistent API across different database
FOR ONLINE READING ONLY
systems, making it an ideal choice for developers working with multiple databases. Chapter Eight: Databases and Database Management Systems
This example is based on the same farming database to demonstrate the basics of
using PDO with MySQL, covering connecting to a database, inserting data, querying
and fetching data, and disconnecting.
Setting up a database connection
First, establish a connection to your database using PDO, as shown by codes in
Program Example 8.10.
Program Example 8.10:
PHP program to establish a connection to database using PDO
php
<button><svg><path></path></svg><span>Copy code</span><span></span></button>
<?php
$host = ‘localhost’;
$db = ‘farming_db’; // Example database name
$user = ‘root’;
$pass = ‘’;
$charset = ‘utf8mb4’;
$dsn = “mysql:host=$host;dbname=$db;charset=$charset”;
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
echo “Connected successfully”;
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
513
Student’s Book Form Five
Computer Science Form 5.indd 513 23/07/2024 12:35

