If you haven't already done so, I would suggest reading Introduction To PDO Part 1 , which explains how to connect to a MySQL server and issue SQL statements using the query() method.
Part 2
When an SQL statement is issued using either the query/prepare method of the PDO class, an instance of PDOStatement is returned. This object represents a prepared statement and holds an associated result set if the SQL statement issued was a SELECT statement. You can then use methods such as fetch(), fetchAll(), fetchColumn() and fetchObject to return data from the result set. Each method mentioned returns data in a different way. For example, the fetch() method will return the next row data from the result set, while fetchAll() will return an array of all rows. Both the fetch() and fetchAll() methods allow you to specify in which format the data should be returned. For example, by default, both methods will return an array indexed by both column name and number, resulting in duplicate data. A sample result is shown below for clarity.- Array
- (
- [user_id] => 1
- [0] => 1
- [first_name] => John
- [1] => John
- [last_name] => Smith
- [2] => Smith
- )
- <?php
- $pdo = new PDO("mysql:dbname=dbname;host=127.0.0.1", "root", "");
- $stm = $pdo->query("SELECT * FROM users");
- $row = $stm->fetch(PDO::FETCH_ASSOC);
- print_r($row);
- ?>
Another useful constant is the FETCH_CLASS constant, which allows you to specify your own class mapping. Class properties must be declared public for mapping to be successful. The code below shows how to map the User class to the result.
- <?php
- class User {
- public $first_name;
- public $last_name;
- }
- $pdo = new PDO("mysql:dbname=dbname;host=127.0.0.1", "root", "");
- $stm = $pdo->query("SELECT * FROM users");
- $stm->setFetchMode(PDO::FETCH_CLASS, "User");
- $user = $stm->fetch();
- print_r($user);
- ?>
The PDOStatement class has a rowCount() method which returns the number of rows affected when either an INSERT,UPDATE or DELETE SQL statement is issued. Most databases don't return the number of affected rows when a SELECT statement is issued. To count the number of rows affected, you can issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use fetchColumn() to retrieve the number of rows that will be returned.
No comments:
Post a Comment