Now that you've got the basics straight, let's evolve the application a little further. Our next example will ask the user to enter a user name. If it's a valid user name, the script will connect to the database and display the corresponding list of URLs; if not, it'll return an error. We'll be using a single page for the entire operation - the $submit variable [you remember this technique, don't you?] is used to decide whether to display the initial form or the result page. Take a look: Log in as "bill" or "john" and watch as PHP connects to the database and retrieves that user's list of sites. If you look closely, you'll see that the script above actually contains three HTML pages embedded within it, one for each of the three possible scenarios. The first time the user visits the page, the variable $submit will not be set, and so a simple HTML form is displayed; this forms asks for a user name, which is stored in the variable $username. Once the form has been submitted, the same page is called again; however, this time around, the $submit variable will be found and so PHP will initiate a connection to the database to check if the user name is valid. One simple technique that can be used for simple "yes/no" type queries [such as the one above] is the mysql_num_rows() function; this function tells you the number of result rows returned by the query. A value of zero implies that no rows were found, which in turn implies that the user was not found. The result of mysql_num_rows() is stored in the variable $num_rows. If this variable exists, it implies that the user name is valid, and it's then possible to move ahead and fetch the Web addresses corresponding to that user name from the database. These addresses are then formatted and displayed on the page as active hyperlinks.
blog comments powered by Disqus |