I l @ ve RuBoard |
Obviously, not all of your data will derive from HTML forms and sometimes you might want to manually set data within your script. If you created a script that printed a user 's name in a greeting, you could establish a variable that contains the name separate from the rest of the greeting. That way you could easily change the name without having to change the greeting, the print statement, or the script itself. We will create a PHP script to demonstrate this process. Script 3.5. Instead of coding the page to automatically say "Hello, World!" or "Hello, Larry!" we have made the page dynamic by printing out the value of a variable instead. Now, as that value changes, so will the resulting page.
To creating a PHP script that displays a greeting:
If you were to view this script now, it would only display "Hello, ." as the $FirstName variable has no value. There are two ways you can manually set this value, without using forms. The first is to use what you know about how the GET method passes data to a script. To use the GET method without an HTML form:
The second way you can preset a variable value is by directly assigning it within the script itself. Script 3.6. The $FirstName = "Jude"; line assigns the value "Jude" to the variable "FirstName" for the existence of this page.
To assign a value to a variable:
The concept of pre-establishing variable values is especially useful as your program gets more complicated. Using an easily edited variable means that you never have to hunt through multiple lines of code to replace one value with another. Likewise, by appending a variable to a URL, you can link one page to a dynamically generated second page (such as hello.php/ ) simply by coding your Web page inks to include variable values, where necessary. For example, one form on a Web site may take the user's first name, and pass that along to subsequent linked pages with the code <A HREF ="hello.php? FirstName=Larry">hello.php </A>. Tip If you want to use the GET method to send data to your script, you can pass multiple values along by separating the variable=value pairs (e.g., FirstName= Larry ) with the ampersand (&). So an appended URL may be hello.php? FirstName=Larry&LastName=Ullman . Tip Spaces within values that are passed as part of a URL should be replaced with a plus sign (+). In Chapter 5, Using Strings, I'll discuss how PHP can automatically prepare a string of text to be passed as part of a URL. Tip Although the example heresetting the value of a person's namemay not be very practical, creating an $email variable at the top of the script would allow you to later change that email address without looking through lines of code to find it. In fact, in Chapter 11, Databases, I'll make it a habit to establish the database access values through variables at the beginning of our scripts so they can be altered easily without changing every instance where those values are used. |
I l @ ve RuBoard |