In the previous section, I explained how to aggregate a new method to the sample “MySQL” class to provide it with the capacity for performing SELECT statements that include a LIKE clause. However, the best way for you to understand how this enhanced version of the class functions is by means of a concrete example. With that idea in mind, I’m going to use the sample “users” MySQL table created in a previous tutorial of this series, which looked like this:
Now that the above MySQL table is available for testing purposes, here’s a simple example that shows how to use the “fetchLike()” method defined earlier to fetch all the users whose first names contain the “a” character: try{ // connect to MySQL and select a database $db=new MySQL('host','user','password','mydatabase'); // display users where first name contains the 'a' character $result=$db->fetchLike('firstname',"'%a%'",'users'); foreach($result as $row){ echo $row['firstname'].' '.$row['lastname'].' '.$row['email'].'<br />'; } /* displays the following Alejandro Gervasio alejandro@domain.com */ } catch(Exception $e){ echo $e->getMessage(); exit(); } Undoubtedly, you’ll have to agree with me that the above example is very simple to grasp, since it uses the aforementioned “fetchLike()” method to perform a basic SELECT query that includes the LIKE clause. Obviously, regardless of its simplicity, the example is helpful for illustrating how to use the active record approach to execute different types of queries by means of a simplified, abstract interface. As usual, feel free to introduce your own modifications to the code samples included in this tutorial. Doing this will surely give you a more solid grounding in using this popular design pattern in PHP 5. Final thoughts In this fourth chapter of the series, you hopefully learned how to use a basic MySQL abstraction class to perform SELECT statements in conjunction with simple LIKE clauses via the active record approach. As you saw before, this process only required coding a straightforward method and putting it to work. It was that simple, really. In the forthcoming episode, I’m going to demonstrate how to utilize the same “MySQL” class coded earlier for running SELECT queries that contain a LIMIT clause. The topic will be juicy, so if you wish to master it in a few steps, then don’t miss the next part!
blog comments powered by Disqus |
|
|
|
|
|
|
|