110 likes | 288 Vues
This guide provides an overview of PHP's PDO (PHP Data Objects) extension, which offers an object-oriented interface for accessing databases. It emphasizes the importance of portability, speed, and security, highlighting features like prepared statements to prevent SQL injection. The tutorial covers basic operations such as connecting to a database, inserting, updating, deleting records, and querying both single and multiple rows. Learn how to instantiate PDO, execute SQL commands, and utilize its methods for effective database management.
E N D
PDO:PHP Data Objects CSCI 215 Tina Ostrander
PDO: What? • PDO - PHP Data Object • An interface for accessing databases in PHP • Provides a data-access abstraction layer • Same functions are used across DBMSs • Object-oriented
PDO: Why? • Portability • Speed • Security • Supports prepared statements • Pre-compiled SQL statements that accept zero or more parameters • Prevents SQL injection by using placeholders for data
Get connected This creates a database object called $dbh try { /*** instantiate a database object ***/ $dbh = new PDO("mysql:host=$hostname;dbname=myDB",$username, $password);echo 'Connected to database';}catch(PDOException $e) { echo $e->getMessage(); }
Insert $sql = "INSERT INTO animals(animal_type, animal_name) VALUES ('kangaroo', 'troy')"; $dbh->exec($sql); //Get the ID of the last inserted row $id = $dbh->lastInsertId(); lastInsertId() returns the ID of the last inserted row
Update $sql= "UPDATE animals SET animal_name='Joey' WHERE animal_name='Troy'"; //exec() returns the number of rows affected $count = $dbh->exec($sql); print "$count rows were updated."; exec() returns the number of rows affected
Delete $sql= "DELETE FROM animals WHERE animal_type='kangaroo'"; //exec() returns the number of rows affected $count = $dbh->exec($sql); print "$count rows were deleted.";
Select One Row //Define the query $sql = "SELECT * FROM animals WHERE animal_id = 3"; //query() returns the result$result = $dbh->query($sql); //fetch() returns the first row$row = $result->fetch();print $row['animal_type'] . ' - '. $row['animal_name']; query() returns a result set fetch() returns a single row
Select Multiple Rows //Define the query $sql = "SELECT * FROM animals"; //query() returns the result$result = $dbh->query($sql); //iterate through the result set foreach($result as $row) { print $row['animal_type'] . ' - '. $row['animal_name']; }
References • PDO Manual • PDO Tutorial I • PDO Tutorial II