HomePHP Page 3 - PHP and JavaScript, Pooling Your Resources (continued)
What Does PHP Do? - PHP
In this article, you will learn how to combine PHP and JavaScript to create two SELECT menus, one containing categories, and the other containing only those options applicable to the category selected.
The reasons for using HTML in our project are obvious, as are the reasons for using JavaScript (hopefully) – but why do we need PHP? PHP provides us with an enormous range of programming options, one of which is an easy mechanism through which to query a MySQL database and receive a result set. This is primarily what we will be using our helper function to do. Let’s take a look now at the code:
<?php function get_parent_menu() { $select_menu = NULL; # establish connection to the MySQL server mysql_connect( 'localhost', 'root', '' ); mysql_select_db( 'devshed' );
# append empty option (to be default) $select_menu .= "\t" . "<OPTION onMouseOver=\"show_hint( 'Please select an option from the list below.' );\" onMouseOut=\"set_timeout();\" value=\"\" SELECTED>- - select - -</OPTION>" . "\r\n";
# retrieve a list of all parent values $db_query = 'SELECT * FROM php_js_parent_menu;'; $db_result = mysql_query( $db_query );
# output a SELECT menu option for each row returned if ( $db_result ) { while ( $l_db_row = mysql_fetch_assoc( $db_result ) ) {
# output SELECT menu with JS attributes $select_menu .= "\t" . "<OPTION onMouseOver=\"show_hint( '$l_description' );\" onMouseOut=\"set_timeout();\" value=\"$l_id\">$l_name</OPTION>" . "\r\n";
} # END while rows } # END if rows
# return SELECT menu return $select_menu;
} # END get_parent_menu() ?>
As you can see above, the ‘get_parent_menu’ function does two basic things. First, it queries the SQL database for all values stored in our ‘parent_menu’ table. It then takes those values, and outputs them in the form of <OPTION> tags for our ‘parent’ SELECT menu.
The only thing that may need additional explanation here is the use of the onMouseOver and onMouseOut events. The application we are developing is pretty self-explanatory to an end-user, but it never hurts to make our systems a little easier to use and understand to someone who may not be adept with computers. Because of that, we have chosen to implement a “hint box” to display helpful tips to the user in real-time. When the user hovers over a menu option, a brief explanation of that option will be displayed in our hint box. When the user moves on a timeout is set to erase the hint after a couple of seconds. This is all done through the use of the JavaScript functions we discussed in the previous section.
We’re now ready to move on to our application’s stylesheet.
How’s it Looking?
Our stylesheet, “stylesheet.css”, is very simple. One class is used to control the appearance and formatting of our SELECT menus, and another is used to control the previously mentioned “hint box”. Those classes are as follows: