createElement

Creates a new form element of the given type. Just like addElement, this method can take a variable number of parameters, depending on the type of element you're creating. object amp createElement mixed element element mixed Either an element object or a string specifying the type of element. If a string, then additional parameters can be included that vary depending on the type of element to add and that are used to create the element.

Calendar.php

The following listing shows the final calendar code. Notice that the numbers at the beginning of each line are not part of the code they appear here to aid in the discussion that follows the listing. Display a calendar and allow user to move forward and backward through months via form controls. month last month displayed year last year displayed calendar TRUE if this script is calling, mini to display miniature calendar Form control POST Next Next month Form control POST Prev Previous month...

How to Initialize Your Own 'library' Classes

Originally, you couldn't make your own classes part of the CI 'super-object'. This was a problem, because it meant that your library code couldn't, for instance, access the database through Active Record, or use other CI libraries, and that became pretty limiting. Version 1.2 added the get_instance function that allows you to access the 'super-object'. See Chapter 7. You could include it in your 'library' or 'script' and then use the CI resources. Unless your new file was a functional script...

getHolidaysForDatespan()

Returns an array of Date_Holidays_Holiday objects for the holidays that occur between the two specified dates. If no holidays are found, then an empty array will be returned. array getHolidaysForDatespan mixed start, mixed end , Date_Holidays_Filter filter null , string locale null start mixed The starting date of the time span. end mixed The end date of the time span. filter to use for loading holidays. locale string The locale to use when loading holiday

Creating a Shopping Cart Class

For the second real-world use of object-oriented programming, I want to implement as a class the shopping cart system created in Chapter 5, E-Commerce Techniques. If you look back at cart.php Script 5.7 , you'll see that the one page does several things Updates the quantities in the cart Removes items from the cart when the user enters a quantity of 0 Displays the shopping cart in an HTML form In an object-oriented structure, this can be implemented in many ways. You could start with an...

My Security Anecdote

In the summer of 2006, I revamped my company's Web site www.DMCInsights.com , using a modularized layout, to a small extent. Literally the first night the new version of the site went live, someone tried hacking the server by changing URLs like about.php i phpmysql2 into about.php i http somesite.com file.txt. The file.txt script on that other server contained PHP code that would reveal every file on my server. Had it run, my site's security would have been compromised. The attempt did not work...

Dreamweaver Template Builder

Since Macromedia Dreamweaver http www.macromedia.com software dreamweaver is among the market leaders when it comes to professional web editors, there was a Mambo template builder for quite a long time. We are talking about a normal Dreamweaver extension that you can install by means of the Macromedia Extension Manager. The Extension Manager is in the same program group as Dreamweaver itself. Figure 2.14 Macromedia Extensions Manager with the Mambo Plug-in Figure 2.14 Macromedia Extensions...

finderQuery Parameter

To produce even more customized results, you may enter a SQL string in the finderOuery key, and it will run when the associated records are queried. You really should need to use this option only if your application requires a high level of database customization. Most of the time, you will be able to work just fine using Cake's built-in model functions. The has many relationship is extremely useful for helping to design effective databases. If you know that you intend to put a select menu in...

tableCells( data[array], oddTrAttributes[array],

data Table data arranged as rows and columns in an array oddTrAttributes null HTML attributes to be passed to odd rows evenTrAttributes null HTML attributes to be passed to even rows useCount false If true, adds the class name column- plus the number of the row to the lt tr gt element The html- gt tableHeaders function renders only the header row inside a table. Be sure to enter the lt table gt element tags by hand as HTML and include these table functions inside this element. The returned HTML...

Introduction to PEAR

As you might imagine, there are plenty of open source libraries available to the PHP language. In fact, one might say that PHP's success as a language is due to the multitude of available resources and the amazing, helpful online community. Because of the large amount of open source development libraries, implementing clean, effective code into your Ajax-based applications is a mere Google search away. However, like anything, some code libraries repositories are better than others. One of the...

C.9.4 Exercise 4:

Load the form element helper functions require 'formhelpers.php' if _POST '_submit_check' If validate form returns errors, pass them to show form if form errors validate form The submitted data is valid, so process it process form The form wasn't submitted, so display show form function show form errors '' if errors print 'You need to correct the following errors lt ul gt lt li gt ' print print ' lt li gt lt ul gt ' print ' lt form method POST input submit 'submit','Show File' the hidden...

Displaying the Entire Contents of a Directory

The example shown here demonstrates how to display the entire contents of a directory by using the maptree function to populate two arrays. One array, directories, contains a list of directory names, while the files array contains a list of files found in the directory that is being mapped. Two loops at the end of the example iterate through the two arrays and print their contents. Displaying the entire contents of a directory require_once 'File Find.php' This example will recursively search...

Binding Parameters 2

You might have noted in the earlier introduction to the execute method that the input_parameters parameter was optional. This is convenient because if you need to pass along numerous variables, providing an array in this manner can quickly become unwieldy. So what's the alternative The bindParam method. Its prototype follows boolean PDOStatement bindParam mixed parameter, mixed amp variable , int datatype , int length , mixed driver_options When using named parameters, parameter is the name of...

Designing a Better View

At this stage, you might ask why we are going through so much effort to serve up a simple HTML page. Why not put everything in one file For a simple site, that's a valid point but whoever heard of a simple site One of the coolest things about CI is the way it helps us to develop a consistent structure, so that as we add to and develop our site, it is internally consistent, well laid out, and simple to maintain. At the start, we need three common steps Update our config file to specify where the...

generateTreeList

This function is a convenience method for returning a hierarchical array to be used in making HTML select boxes or breadcrumbs. generateTreeList amp model, conditions mixed , keyPath string , valuePath string , spacer string , recursive int conditions null SQL conditions as a string or as an array similar to conditions used in the find model function keyPath null A string path to the key, for example, n .Tag.name valuePath null A string path to the value similar to keyPath spacer '_' For each...

addCrumb( name[string], link[mixed], attributes[array] )

link null Can be keyed in an array for example, or entered as a string for example, ' posts add' if left blank, no link will be rendered around the text attributes HTML attributes to be passed to the lt a gt tag of the crumb Adding the home page of the site to the breadcrumbs array, for example, is simple using this function To display the breadcrumbs, however, you must use the html- gt getCrumbs function. Some parameters exist for the html- gt getCrumbs function to better manipulate how these...

Adding, Moving, and Removing Notebook Pages

Each page of a notebook has two elements the tab and the content. The page tab is usually a string that describes the contents of the page. The tab is the main method by which a user will select a page. The content of the page can be anything. Usually, the content that is added directly to the page is some sort of container. A page can be added at the beginning of a notebook, at the end of a notebook, or anywhere in between using the methods prepend_page, append_page, and insert_page,...

Interacting with Controllers

You can call libraries, models, plug-ins, or helpers from within any controller, and models and libraries can also call each other as well as plug-ins and helpers. However, you can't call one controller from another, or call a controller from a model or library. There are only two ways that a model or a library can refer back to a controller Firstly, it can return data. If the controller assigns a value like this fred this- gt mymodel- gt myfunction and the function is set to return a value,...

dependent Parameter

When deleting records in a has one relationship, you may want both sides of the association to be deleted. For example, when a user has one profile and the user is deleted, you may want the associated profile to be deleted also. In these cases, the dependent key allows you to do this easily. By default, it is set to false. Set dependent to true to delete records in both tables when the delete action is run through the associated model. In the blog you are building, you have no need of a has one...

One-way communication

One-way communication in Flash is the process of sending data to a Web server and not looking or caring if a response comes back. This is mostly used to open a URL, but could also be used to update a file with no intention of handling the result. This type of communication is often used for simply firing off an event or running some sort of cleaning system. For example, if your site needs periodic file cleaning deleting, renaming, moving , it is a good idea to attach this to the front-end...

The foreachelse Function

The foreachelse function is used in conjunction with foreach, and operates much like the default tag does for strings, producing some alternative output if the array is empty. An example of a template using foreachelse follows foreach key key item item from titles key item lt br gt foreachelse lt p gt No states matching your query were found. lt p gt foreach Note that foreachelse does not use a closing bracket rather, it is embedded within foreach, much like an elseif is embedded within an if...

Setting Variables

The SET statement is used to set the value of a declared stored routine variable. Its prototype looks like this SET variable_name value , variable_name value The following example illustrates the process of declaring and setting a variable titled inv It's also possible to set variables using a SELECT INTO statement. For example, the inv variable can also be set like this SELECT inventory INTO inv FROM product WHERE productid MZC38373 Of course, this variable is local in scope to the BEGIN END...

Running SQL statements with MySQLGUI

Running a query or other SQL statement is really quite simple with MySQLGUI. Simply type the query into the box as shown in Figure 8-40, using a simple query on the mysql database such as SELECT FROM user. Choose Execute 1 Save , L , . Clear Options tables query queiy 1 j Fuuiul 9 tables Info Figure 8-40 Executing SQL statements with MySQLGUI is easy, as shown by this simple query. You can choose of what you'd like to do with the results from the statement. Figures 8-36 through 8-39 show three...

Understanding How PHP Works with Apache

Apache uses MIME types to determine how to serve up specific files. For example, look at the PHP MIME type definition in the Apache configuration file AddType application x-httpd-php .php .phtml Whenever Apache is asked to serve up a file with a .php or .phtml extension, it identifies the file as a PHP file and utilizes the appropriate module the PHP module to help serve it. In PHP's case, the module provides communication with the PHP engine. The engine executes the PHP code and directs any...

"Has and Belongs to Many"

The final association Cake can recognize for database table relationships is the has and belongs to many relationship. This relationship is powerful but also a little difficult to master. The more you experiment with has and belongs to many associations, the easier it will be to use them in your applications. In short, I've already discussed a one-to-one relationship with the hasOne association, and the hasMany association shows you how a one-to-many relationship is managed in Cake. What about...

Validating Multiple-Choice Input

Checkboxes and drop-down lists are an important component of web forms, and it's often necessary to include validation for these controls in your PHP applications. Normally, the user's selections from these controls are submitted to the form processor in the form of an array, and it's necessary to use PHP's array functions to validate them. To see this in action, consider the following script, which requires the user to fill out a brief user profile and select at least three hobbies and two...

Installing a Third-Party Script

Now that I've covered the basics of installing a vendor, let's use a third-party script in your blog application. Rather than build a wiki engine from scratch, let's choose one of the many open source text-parsing engines Textile. First, obtain a copy of Textile, which is available at http textile.thresholdstate.com. In this tutorial, I'll be using version 2.0. Once you have downloaded the file and decompressed it, you'll find the main engine file named classTextile.php. Place this file in the...

Using the UNIQUE Modifier

Using MySQL's built-in validation mechanisms has an important advantage it makes it easy to perform certain types of validation that would be lengthy and time-consuming to write code for. Consider, for example, the situation of ensuring that a particular field contains only unique values. MySQL makes it possible to do this, simply by attaching a UNIQUE modifier to the field, as in the following example - gt username VARCHAR 50 NOT NULL UNIQUE Query OK, 0 rows affected 0.06 sec mysql gt INSERT...

Writing shopping_product_page.inc

The shopping_product_page.inc and shopping_product_page-oo.inc files are very similar to the catalog_product_page.inc and catalog_ product_page-oo.inc files in Chapter 5. However, a few additions are required that allow the customer to order online. The file with the additions is shown in Listing 6-2. I describe only the lines that are changed in this section. For a complete description of all the lines, see the section Writing the code for the products page in Chapter 5. The file for the...

selectByID

This method retrieves a single row from the table. The row is identified by its id column. selectBylD doesn't return the content of the row, it returns TRUE or FALSE to indicate whether the requested row was found. If the selectByID function can't find the row that is being looked up, it stores a message in the object explaining that no such object exists in the data that can be retrieved by calling the getMessage method. The following numbers refer to line number in Listing 8-17. 38 Because...

Turning Off Verbose Error Reporting

You usually want to turn off verbose error reporting in production scripts. The main reason for this has to do with security you don't want users seeing too much of the man behind the curtain. For example, PHP usually outputs something similar to the following if it fails to connect to a database Warning Access denied for user 'username localhost' Using password YES in var www html errortest.php on line 11 Warning MySQL Connection Failed Access denied for user 'username localhost' Using...

Using Decimal and Comma Separators

When it comes to formatting numeric values in PHP, there are only two functions number_format and sprintf . Of these, the former is easier to understand and use, so let's begin with that function. The number_format function is used to display large numbers with comma and decimal separators. It can be used to control both the visibility and the appearance of the decimal digits, as well as the character used as the thousands separator. To see how this works, consider the following table mysql gt...

loginHandler method

The loginHandler method is attached to the CLICK event of the loginBtn. This method is called whenever the loginBtn is clicked by the mouse. private function loginHandler e MouseEvent void This method is responsible for checking the username and password fields for valid data. If one of these fields is empty, the function is exited and a response message is displayed below the password field. loginMC.responseTxt.text if loginMC.username.text loginMC.password.text loginMC.responseTxt.text...

Sorting multidimensional arrays

Sorting arrays is easy using PHP, thanks to the sort , ksort , and related functions. You can sort a one-dimensional array by key, by value, in reverse order, etc. But these functions will not work on multidimensional arrays not as you'd probably like, at least . Say you have an array defined like so a array array 'keyl' gt 940, 'key2' gt 'blah' , array 'keyl' gt 23, 'key2' gt 'this' , array 'keyl' gt 894, 'key2' gt 'that' This is a simple two-dimensional array an array whose elements are also...

The MySQLResultSet Class

Not surprisingly, the MySQLResultSet class shown in Listing 9-1 has more data members and methods than the MySQLConnect class. However, in many ways, it's a much simpler class and requires much less explanation. To get an overview of this class, find all its data members and methods listed here data members private strSQL private databasename private connection private result public methods public function _construct strSQL, databasename, connection return current record public function getRow...

Creating an RSS Feed

RSS, which stands for Really Simple Syndication it used to mean Rich Site Summary or RDF Site Summary , is a way for Web sites to provide listings of the site's content. Normally this list contains at least the titles of articles, plus their descriptions and by article, think of any type of content that a site might offer . Users access these feeds using an RSS client many Web browsers support RSS, as well . If they want to read more of an article, there's a link to click, which takes them to...

The Articles Table

The articles table is the heart of the system, storing all articles for retrieval via various utility programs. The articles table needs to store the following pieces of data An index to uniquely identify the article The publication date of the article The category to which the article is assigned A short title for the article The full text of the article A field to identify the article as a draft or a final copy The MySQL create statement for this table is as follows idx int 10 unsigned NOT...

Extending Sqlite

SQLite comes packaged with PHP 5. It has advanced capabilities and a built-in object-oriented OO interface. Examining the classes and methods of SQLite is the ostensible reason for including this chapter but that's not the only reason. SQLite is a great addition to PHP, but because MySQL is so entrenched, programmers tend to ignore SQLite. Don't let the Lite in SQLite lead you to underestimate the capabilities of this database. Because it is bundled with PHP, there is no external server to...

Confirming Important Actions Using a One-Time Token

If a user tries to do something that has some importance such as transferring funds, changing password, or buying goods , make them confirm their intentions before processing the transaction. In the preceding example, the Insecure Bank Co. shouldn't have transferred the money to Bob's account so easily. Julie should have been forced to fill out a specific form for the transaction to take place. In this form, you use a one-time token. This is essentially a password that is generated for a...

SHOW GRANTS FOR

The SHOW GRANTS FOR lt user gt statement, which I refer to simply as SHOW GRANTS, enables you to find out quickly the privileges that a given user has on a server and the statements you would have to issue if you were to give that user those same privileges. For example, one task I am confronted with frequently is giving a user access to a new database system as new servers are implemented. The user almost always needs the same access as they have on the existing system. Using the SHOW GRANTS...

To create the configuration file:

1. Begin a new PHP script in your text editor or IDE Script 2.1 . lt php Script 2.1 - config.inc.php Script 2.1 The configuration file is the key back-end script. It defines site-wide constants and dictates how errors are handled. 1 lt php Script 2.1 - config.inc.php 5 Created by Larry E. Ullman of DMC Insights, Inc. 6 Contact LarryUllman DMCInsights.com, http www.dmcinsights.com 7 Last modified November 8, 2006 9 Configuration file does the following things 10 - Has site settings in one...

Using the Amazon Web Service

To get started with creating a developers account, visit the Amazon Web Service AWS page at www.amazon.com gp aws landing.html. j j' J'j Be sure to activate the account via e-mail before you begin to use it. The AWS is set up to be accessed from different mediums. The format used for this example is Representational State Transfer REST , which is basically a formatted URL with all of the necessary information provided in GET format. Here is a sample request sent to Amazon, as shown in Figure...

The MySQLException Class

You can improve the functionality of a class when using inheritance by adding new methods or changing inherited ones. Changing inherited methods of a class is called overriding. In this particular case, the number of changes you can make to existing methods by overriding them is severely limited because, as you saw in Listing 10-1, there are only two non-final methods of the Exception class the constructor and the_toString method. Let's change both of these class MySQLException extends...

Is It the Holy Grail?

One very legitimate concern might be voiced over the inclusion of the SQLite-specific method sqliteCreateFunction, and this is certainly not the only database-specific capability provided by PDO.3 Doesn't providing database-specific functionality do exactly what we refrained from doing at the start namely, extending the PDO class The short answer is, unquestionably, yes. But the whole notion of a perfect database abstraction layer is a Holy Grail glimpsed here and there but never grasped....

Your first database

Now that we have PHP running properly and have created our first script, let's create our first database and see what we can do with it. Drop to console and type in the following command This creates a database named learndb for us to use. Here we have assumed that you are root user. If you are logged in as another user, just use the command mysqladmin -uusername -pyourpassword create learndb, replacing username and yourpassword with your username and password respectively. If you are hosting...

allow_call_time_pass_reference = On | Off

Scope PHP_INI_SYSTEM Default value On Function arguments can be passed in two ways by value and by reference. Exactly how each argument is passed to a function at function call time can be specified in the function definition, which is the recommended means for doing so. However, you can force all arguments to be passed by reference at function call time by enabling allow_call_time_pass_reference. The discussion of PHP functions in Chapter 4 addresses how functional arguments can be passed both...

The Test Suite

Remember those 'test blocks' in the delete function Their purpose is simply to detect if the function is being run 'for real' or for a test, and, if the latter, to make sure that it returns a value we can easily test. This is all because, at the end of the CRUD model, we have a 'self-test' suite. This is called by the test function in any controller it doesn't matter which one and performs generalized CRUD tests using a dummy table. First in the CRUD class there is a master 'test' function,...

string 2

A string element is used for the string data type. In PHI many things are strings. No date or binary types exist, because these are handled using strings. As you will see with the next two types, you do not always have a direct one-to-one mapping of a native PHP data type to an XML-RPC type. In terms of usage within PHP you can use the string element when the data is to be interpreted textually rather than what is held within the string, such as a date time value. This is the syntax PHP Data...

Caching a template fragment

Many times the slot and page types will be too large for the templates of an application. For instance, the list of users can show a link of the last accessed user, and this information is dynamic. Would that mean that nothing can be cached Thankfully not. Symfony allows you to cache fragments of a template with the cache helper. The listSuccess.php template could be written as follows lt php echo link_to 'last accessed user', 'user show id '. last_accessed_user_id gt lt uncached HTML gt lt php...

Creating a MySQL Database

You're going to create a database called store. The CREATE DATABASE command works like this If this works, you'll get a result like this one Database names cannot contain any spaces. On Unix servers, such as Linux and Mac OS X, database names are also case-sensitive. To start using this database, type USE store You will get the result Database changed. Assuming you've done everything correctly, you'll be set up with new data, and it will be selected for use. Creating tables to hold data is an...