PHP Page 3 - Coding Examples of the Iterator, Countable and ArrayAccess SPL Interfaces in PHP 5 |
If you’re like me, then you want to learn how to work with the previous “MySQLi_ResultWrapper” class, right? Below I coded a script that shows the benefits of making this class an implementer of the Iterator interface. The script in question is as follows: <?php
try { // connect to MySQL $db = MySQLiWrapper::getInstance(array('host', 'user', 'password', 'database'));
// perform query $result = $db->runQuery('SELECT * FROM users');
// traverse rows in result set foreach ($result as $user) { echo '<p>First Name: ' . $user->fname . ', Last Name : ' . $user->lname . '</p>'; }
// reset result pointer $result->rewind();
// display result pointer echo 'Result pointer : ' . $result->key();
// display data in current row $user = $result->current(); echo '<p>First Name: ' . $user->fname . ', Last Name : ' . $user->lname . '</p>';
// move forward result pointer $result->next();
// display result pointer echo 'Result pointer : ' . $result->key();
// display data in current row $user = $result->current(); echo '<p>First Name: ' . $user->fname . ', Last Name : ' . $user->lname . '</p>';
// reset result pointer $result->rewind(); }
// catch exceptions catch(Exception $e) { echo $e->getMessage(); exit(); } As the above code sample shows, it’s extremely easy to traverse a database result set by using a “foreach” loop. Once the data have been fetched from a sample “users” table, thanks to the implementation of the Iterator interface, traversing the records is a breeze. In addition, the example demonstrates how to explicitly use the “rewind(),” “current()” and “key()” methods, which allow you to freely navigate the result set. So far, so good. Now that you've grasped the logic driving the previous code sample, it’s time to show how to use the “count(),” “offsetExists()” and “offsetGet()” methods. This example will be the appropriate conclusion to this tutorial, so click on the link that appears below and read the following segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|