O'Reilly logo

Managing & Using MySQL, 2nd Edition by Hugh E. Williams, Randy Yarger, George Reese, Tim King

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Implementing the Model

In the rest of this chapter, we’ll lay out the code that implements a robust Model for a class we’ll call Publisher . For the sake of simplicity, each publisher has just two attributes: an ID and a name. The id field is the primary key and uniquely identifies each row of the table. The Name field is the name of the publisher.

In this class, you will recognize all the methods we discussed in the previous section. Of the 13 methods, 4 correspond directly to SQL activities:

create( )

An instance method that inserts a new row into the table to hold the data from this object. The primary key for this table is a MySQL AUTO_INCREMENT field that automatically creates a new value for that field. Therefore, this method inserts only the value of the name field. The id field is passed in by this method as NULL, set in the database by MySQL, and then retrieved and assigned to the object’s id attribute by this method.

get( )

A static method that creates an SQL SELECT statement based on WHERE parameters passed to the function. For each row of the result set, a new object is created and an array of these objects is returned. This method represents the Generic Where method described in the previous section.

remove( )

An instance method that removes the row of data corresponding to this object in the database. It issues an SQL DELETE command to accomplish the removal. After this method is called, the program should destroy the object, because its underlying data is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required