As I expressed in the introduction, it’d be instructive to demonstrate how to update in cascade the comments posted on a particular blog entry by using a popular server-side scripting language like PHP 5. To do so, it’s necessary to build a piece of code that allows us to access the InnoDB tables shown in the previous segment, which in this particular case will be a basic MySQL abstraction class built in PHP 5. Having explained that, here’s the complete source code corresponding to this brand MySQL-accessing class. Look at it, please: class MySQL { private $result = NULL; private $link = NULL;
// connect to MySQL public function __construct($host, $user, $password, $database) { if (FALSE === ($this->link = mysqli_connect($host, $user, $password, $database))) { throw new Exception('Error : ' . mysqli_connect_error()); } }
// perform query public function query($query) { if (is_string($query) AND empty($query) === FALSE) { if (FALSE === ($this->result = mysqli_query($this->link, $query))) { throw new Exception('Error performing query ' . $query . ' Error message :' .mysqli_error($this->link)); } } }
// fetch row from result set public function fetch() { if (FALSE === ($row = mysqli_fetch_object($this->result))) { mysqli_free_result($this->result); return FALSE; } return $row; }
// get insertion ID public function getInsertID() { return mysqli_insert_id($this->link); } // count rows in result set public function countRows() { if ($this->result !== NULL) { return mysqli_num_rows($this->result); } } // implement destructor to close the database connection function __destruct() { mysqli_close($this->link); } }
As shown above, the MySQL abstraction class that I just defined is very simple to follow. It presents some useful methods for performing queries, counting rows in a result set and getting insertion IDs. Quite possibly the most important facet to note is that the class internally uses the “mysqli” PHP extension to interface with MySQL, but other than that detail, the class’s code should be easy for you to understand. Well, now that there’s a PHP 5 class that can be used for interacting with MySQL databases, we need to use its API for executing cascaded updates on the InnoDB tables defined in the previous section. This will be the perfect conclusion to this tutorial, so to see how the “MySQL” class will be utilized in conjunction with the tables, read the following section.
blog comments powered by Disqus |
|
|
|
|
|
|
|