Building a List Box from a FieldBoth smartRToEdit()and

October 31, 2006 on 7:29 pm | In php | No Comments

Creating a Button That Returns Users to the Main PageTo simplify navigation, I added a button at the end of each PHP program thatreturns the user to the program s primary page. The mainButton()program cre- ates a very simple form calling whatever program is named in the $mainProgramvariable, which is indicated at the top of the library. function mainButton(){ // creates a button to return to the main programglobal $mainProgram; $output .= <<

HERE; return $output; } // end mainButtonSummaryThe details of the SpyMastersystem can be dizzying, but the overall effect is a flex- ible design that you can easily update and modify. This system can accept modi- fications to the underlying database and can be adapted to an entirely differentdata set with relatively little effort. Although you didn t learn any new PHP syntax in this chapter, you saw an exam- ple of coding for reuse and flexibility. You learned how to use includefiles to sim- plify coding of complex systems and how to build a library file with utilityroutines. You learned how to write code that can be adapted to multiple data setsand code that prevents certain kinds of user errors. You learned how to build pro- grams that help tie together relational data structures. The things you havelearned in this chapter form the foundation of all data-enabled Web programming, which in turn form the backbone of e-commerce and content-management systems.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

Building a List Box from a FieldBoth smartRToEdit()and

October 31, 2006 on 7:29 pm | In php | No Comments

Building a List Box from a FieldBoth smartRToEdit()and tToAdd()need drop-down HTML lists following a specificpattern. In both cases, I needed to build a list that allows the user to select a keyvalue based on some other field in the record. This list should be set so any valuein the list can be indicated as the currently selected value. The fieldToList() function takes four parameters and uses them to build exactly such a list. function fieldToList($tableName, $keyName, $keyVal, $fieldName){ //given table and field, generates an HTML select structure//named $keyName. values will be key field of table, but//text will come from the $fieldName value. //keyVal indicates which element is currently selectedglobal $dbConn; $output = ?; $query = SELECT $keyName, $fieldName FROM $tableName ?; $result = mysql_query($query, $dbConn); $output .=

\n ?; return $output; } // end fieldToListThe fieldToList()function begins by generating a query that returns all recordsin the foreign table. I build an HTML SELECTobject based on the results of thisquery. As I step through all records, I see if the current record corresponds to the$keyValparameter. If so, that element is selected in the HTML. 426PHP5/MySQLProgrammingfortheAbsoluteBeginner
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

$fieldName $valList HERE; } else { //it s an

October 31, 2006 on 9:39 am | In php | No Comments

The INSERTstatement that this function creates uses NULLas the primary keyvalue, because all tables in the system are set to AUTO_INCREMENT. I used the sameregular expression trick as in smartRToEdit()to recognize foreign key references. If they exist, I built a drop-down list with fieldToList()to display all possible val- ues for that field and send an appropriate key. Any field not recognized as a primary or foreign key will have an ordinary textbox. Processing an Added RecordThe tToAdd()function sends its results to processAdd.php, which reorganizes thedata much like updateRecord.php. The field names and values are converted toarrays, which are passed to the procAdd()function. function procAdd($tableName, $fields, $vals){ //generates INSERT query, applies to databaseglobal $dbConn; $output = ?; $query = INSERT into $tableName VALUES ( ; foreach ($vals as $theValue){ $query .= $theValue , ; } // end foreach//trim off trailing space and comma$query = substr($query, 0, strlen($query) - 2); $query .= ) ?; $output = query is $query
\n ?; $result = mysql_query($query, $dbConn); if ($result){ $output .=

Record added

\n ?; } else { $output .=

There was an error

\n ?; } // end ifreturn $output; } // end procAddThe main job of procAdd()is to build an SQL INSERTstatement using the resultsof tToAdd(). This insert is passed to the database and the user receives a reportabout the insertion attempt s outcome.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

$fieldName $valList HERE; } else { //it s an

October 31, 2006 on 9:39 am | In php | No Comments $fieldName $valList

HERE; } else { //it s an ordinary field. Print a text box$output .= << $fieldName

HERE; } // end if$fieldNum++; } // end while$output .= <<

HERE; return $output; } // end tToAdd424PHP5/MySQLProgrammingfortheAbsoluteBeginner
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

The primary job of updateRec()is to build an

October 30, 2006 on 9:26 pm | In php | No Comments

The primary job of updateRec()is to build an SQL UPDATEstatement based on theparameters passed to it. It is expecting a table name, an array containing fieldnames, and another array containing field values. The UPDATEstatement is pri- marily a list of field names and values, which can be easily obtained with a forloop stepping through the $fieldsand $valsarrays. Once the query has been created, it is submitted to the database. The success orfailure of the update is reported back to the user. Deleting a RecordDeleting a record is actually pretty easy compared to adding or updating. Allthat s necessary is the table name, key field name, and key field value. ThedeleteRec()function accepts these parameters and uses them to build an SQLDELETEstatement. As usual, the success or failure of the operation is returned aspart of the output string. function delRec ($table, $keyName, $keyVal){ //deletes $keyVal record from $tableglobal $dbConn; $output = ?; $query = DELETE from $table WHERE $keyName = $keyVal ?; print query is $query
\n ?; $result = mysql_query($query, $dbConn); if ($result){ $output =

Record successfully deleted

\n ?; } else { $output =

Error deleting record

\n ?; } //end ifreturn $output; } // end delRecAdding a RecordAdding a new record is much like editing a record. It is a two-step process. Thefirst screen builds a page in which you can add a record. I used techniques fromthe smartRToEdit()function to ensure the primary and foreign key references areedited appropriately. function tToAdd($tableName){ //given table name, generates HTML form to add an entry to the//table. Works like smartRToEdit in recognizing foreign keys422PHP5/MySQLProgrammingfortheAbsoluteBeginner

Hint: If you are looking for high quality and reliable webspace provider to host and run your jsp hosting application check Virtualwebstudio jsp web hosting provider

The primary job of updateRec()is to build an

October 30, 2006 on 9:26 pm | In php | No Comments

global $dbConn; $output = ?; //process a query just to get field names$query = SELECT * FROM $tableName ?; $result = mysql_query($query, $dbConn); $output .= <<

HERE; $fieldNum = 0; while ($theField = mysql_fetch_field($result)){ $fieldName = $theField->name; if ($fieldNum == 0){ //it s the primary key field. It ll be autoNumber$output .= <<

HERE; } else if (preg_match( /(.*)ID$/ ?, $fieldName, $match)) { //it s a foreign key reference. Use fieldToList to get//a select object for this field$valList = fieldToList($match[1],$fieldName, 0, name ?); $output .= <<

Hint: If you are looking for high quality and reliable webspace provider to host and run your jsp hosting application check Virtualwebstudio jsp web hosting provider

I used this statement to determine whether a

October 30, 2006 on 10:14 am | In php | No Comments

these values and converts them into arrays before calling the updateRec()func- tion. It s much easier to work with the fields and values as arrays than in thesomewhat amorphous context they embody after smartRToEdit()or rToEdit(). function updateRec($tableName, $fields, $vals){ //expects name of a record, fields array values array//updates database with new valuesglobal $dbConn; $output = ?; $keyName = $fields[0]; $keyVal = $vals[0]; $query = ?; $query .= UPDATE $tableName SET \n ?; for ($i = 1; $i < count($fields); $i++){ $query .= $fields[$i]; $query .= = ; $query .= $vals[$i]; $query .= ,\n ?; } // end for loop//remove last comma from output$query = substr($query, 0, strlen($query) - 2); $query .= \nWHERE $keyName = $keyVal ?; $result = mysql_query($query, $dbConn); if ($result){ $query = SELECT * FROM $tableName WHERE $keyName = $keyVal ?; $output .=

update successful

\n ?; $output .= new value of record:
?; $output .= qToTable($query); } else { $output .=

there was a problem…

$query

\n ?; } // end ifreturn $output; } // end updateRec421Chapter
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

I used this statement to determine whether a

October 30, 2006 on 10:14 am | In php | No Comments

I used this statement to determine whether a field is a foreign key: } else if (preg_match( /(.*)ID$/ ?, $col, $match)) { It uses a simple but powerful regular expression: /(.*)ID$/. This expressionlooks for any line that ends with ID. (Recall that the $indicates the end of astring.) The .*indicates any number of characters. The parentheses around .*tellPHP to store all the characters before IDinto a special array, called $match. Since there s only one pattern to match in this expression, all the characters before IDcontain the table name. So, this regular expression takes thename of a field and determines if it ends with ID. If so, the beginning part of the field name (everything but ID) is stored to $match[1]. If $colcontainsoperationID, this line returns TRUE(becauseoperationIDends with ID) andthe table name (operation) is stored in $match[1]. Building the Foreign Key List BoxIf a field is a foreign key reference, it is necessary to build a list box containingsome sort of meaningful value the user can read. Since I need this capability ina couple of places (and smartRToEdit()is already pretty complex), I build a newfunction called fieldToList(). This function (explained in detail later in the Building a List Box from a Field ? section of this chapter) builds a drop-downHTML list based on a table and field name. Rather than worrying about thedetails of the fieldToList()function here, I simply figured out what parametersit would need and printed that function s results. Working with Regular FieldsAny field that is not a primary or foreign key is handled by the elseclause, whichprints out an rToEdit()-style textbox for user input. This textbox handles allfields that allow ordinary user input, but will not trap for certain errors (such asstring data being placed in numeric fields or data longer than the underlyingfield accepts). These would be good code improvement. If the data designer didnot name foreign key references according to my convention, those fields are stilleditable with a textbox, but the errors that could happen with rToEdit()areworth concern. Committing a Record UpdateThe end result of either rToEdit()or smartRToEdit()is an HTML form containinga table name and a bunch of field names and values. The updateRecord.phptakesTRICK420PHP5/MySQLProgrammingfortheAbsoluteBeginner
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

HERE; return $output; } // end smartRToEditWhat makes

October 29, 2006 on 10:18 pm | In php | No Comments

function allows the user to type any index number into the textbox with- out any real indication what data correlates to that index. This versionbuilds a drop-down list showing operation names. The key value associatedwith those names is stored in the value attribute of each option. (Detailsto follow in the fieldToList()function.) The user doesn t have to knowanything about foreign key references or relational structures he simplychooses an operation from a list. That list is dynamically generated eachtime the user chooses to add a record, so it always reflects all the opera- tions in the agency. Neither a primary nor secondary key.In this case, I print a simple textboxso the user can input the value of the field. In all cases, the output willreflect the current value of the field. Working with the Primary KeyThe primary key value is much more important to the program than it is to theuser. I decided to display it, but not to make it editable in any way. Primary keysshould not be edited, but changed only by adding or deleting records. I relied upon some conventions to determine whether a field is a primary key. Iassumed that the first field of the record (field number 0) is the primary key. Thisis a very common convention, but not universal. Since I created the data design inthis case, I can be sure that the number 0 field in every table is the primary key. For that field, I simply printed the field name and value in an ordinary HTML tablerow. I added the key s value in a hidden field so the next program has access to it. Recognizing Foreign KeysUnfortunately, there is no way (at least in MySQL or SQLite) to determine if a fieldis a foreign key reference. I had to rely on a naming convention to make sure myprogram recognizes a field as a foreign key reference. I decided that all foreignkey fields in my database will have the foreign table s name followed by the valueID. For example, a foreign key reference to the operationtable will always becalled operationIDin my database. This is a smart convention to follow anyway, as it makes your field names easy toremember. It becomes critical in smartRToEdit()because it s the only way to tellwhether a field is a foreign key reference. I used an else ifclause to check thename of any field that is not the primary key (which was checked in the ifclause). The preg_match()function lets me use a powerful regular expressionmatch to determine the field s name.
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check Actions tomcat hosting services

HERE; return $output; } // end smartRToEditWhat makes

October 29, 2006 on 10:18 pm | In php | 1 Comment

HERE; return $output; } // end smartRToEditWhat makes this function smart is its ability to examine each field in the recordand make a guess about what sort of field it is. Figure 12.13 shows the result ofthe smartRToEdit()program so you can compare it to the not-so-clever functionin Figure 12.12. Determining the Field TypeAs far as this function is concerned, three field types in a record need to be han- dled differently. Primary key.If a field is the primary key, its value needs to be passed on tothe next program, but the user should not be able to edit it. Foreign key.If a field is a foreign key reference to another table, the usershould only be able to indirectly edit the value. The best approach is tohave a drop-down list box that shows values the user will recognize. Eachof these values corresponds to a key in that secondary record. For example, in Figure 12.13 there is a list box for the operationIDfield. The operationIDfield is a foreign key reference in the agenttable. The ordinary rToEdit() 418PHP5/MySQLProgrammingfortheAbsoluteBeginnerFIGURE 12.13The smarterfunction preventsthe user fromediting the primarykey and provides adrop-down list forall foreign keyreferences.
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check Actions tomcat hosting services

Next Page »

Powered by cheap hosting

Field Value
$fieldName AUTONUMBER