Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 81 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
81
Dung lượng
597,81 KB
Nội dung
Chapter 5 Control Structures IN THIS CHAPTER ◆ Understanding the syntax of if statements ◆ Determining true and false values with PHP ◆ Learning PHP loops ◆ Choosing loops to use in your scripts CONTROL STRUCTURES ARE the building blocks of programming languages. PHP has all the control structures needed to make a language work. If you’re familiar with C or Perl, none of the features we discuss in this chapter should come as much of a surprise. However, if you’re approaching PHP from a background in VBScript or Visual Basic, the syntax will probably be different from what you’re used to. (If you aren’t familiar with functions, you might want to peek ahead to the beginning of the next chapter for a quick overview — but come right back!) If you find the syn- tax to be a little heavy at first, stick with it. You might find that the extra brackets and parentheses actually help you write readable code. The if Statement The if statement is pretty much the cornerstone of all programming languages. In PHP, an if statement typically takes this basic form: if (condition or set of conditions) { actions to perform if condition is true. } After the word if is a set of parentheses. Within those parentheses is the single condition or set of conditions to be tested. If the condition is evaluated as being true, the code within the curly braces will execute. The following will test true and print “I’m True!” to a Web page. 117 <?php $foo = 100; $bar = 10; if ($foo > $bar) { echo “I’m True!”; } ?> This is clear enough. But before we mention the complexities of the if state- ment, you should know how PHP determines whether a condition is true or false. Determining true or false in PHP The next section shows the operators commonly used in if statements. These are fairly easy to understand. In the preceding code example, 100 is greater than 10, so ($foo > $bar) will test true. No problem. But there’s a bit more to these tests in PHP. The words TRUE and FALSE also carry the expected meanings. if (TRUE) { echo “Yup!”; //this will be printed } if (FALSE) { echo “Nothing doing.”; //this will not be printed } But you’re not limited to simple mathematical operators or the words TRUE and FALSE when you’re testing for a true or false condition. As you can see in Chapter 4, you often test for the existence of a variable using isset() or empty(). These functions, like many others in PHP, return a value of FALSE if the condition is false, and a value of TRUE if the condition is true. If used as a simple value, FALSE con- verts to 0 and TRUE to 1. For example, the following prints out “1”: $myvar = “I am setting a variable”; echo isset($myvar), “\n”; But though FALSE and 0 are equivalent (just as 0 and an empty string are equiv- alent) and TRUE and 1 are equivalent, they are not the same. You can see this using 118 Part II: Working with PHP the built-in PHP function var_dump(), which shows you the internal representa- tion of a value. If we use it with the previous example: $myvar = “I am setting a variable”; var_dump(isset($myvar)); the output is now “bool(true)”. When you need to test if two values are not just equivalent, but identical, you use the === operator (or !== to test if the values are not identical). The following shows you what we mean: $myvar = “I’m setting a variable again”; if (isset($myvar) == 1) echo “isset(\$myvar) is equivalent to 1\n”; if (isset($myvar) === 1) echo “isset(\$myvar) is exactly the same as 1\n”; if (isset($myvar) == TRUE) echo “isset(\$myvar) is equivalent to TRUE\n”; if (isset($myvar) === TRUE) echo “isset(\$myvar) is exactly the same as TRUE\n”; The output of this code is: isset($myvar) is equivalent to 1 isset($myvar) is equivalent to TRUE isset($myvar) is exactly the same as TRUE It’s not just 1 that is true—any non-zero, non-empty value tests as true (an array with no elements is empty, so it tests as false). This gives you some flexibility in your tests. When working with Web pages, you’ll usually be doing some sort of text manip- ulation. Often you’ll need to test whether the text string you’re working with has a certain structure. For example, you might want to test whether a string contains certain characters. You can use one of the regular expression functions for this, but you can also use the strstr() function. The strstr() function takes two argu- ments, both of them strings. It searches the first argument for the first occurrence of the string specified in the second argument. It returns the string in the second argument plus all of the characters following that string. However, if the string isn’t found, the function will return a value of FALSE. In the following example strstr() returns “text string”: $str = “my little text string”; strstr($str, “text”); Chapter 5: Control Structures 119 Since the result of this function is not empty and not 0 it can be used in a test. The following code would test TRUE and print out “Yeah!” $str = “my little text string”; if (strstr($str, “text”)) { echo “Yeah!”; } But in the string is not found in the following example, so the function will return a value of FALSE and nothing will print: $str = “my little text string”; $new_str = strstr($str, “nothing”); if ($new_str) { echo “nothing to print”; //this will not be printed } However, you need to be careful with these kinds of simple tests. For instance, using strstr() just to test if one string contains another is something of a waste of resources — it’s handing you back a whole substring value that you don’t need. So say you decide to use the strpos() function instead. This built-in function returns the position of one string within another, or FALSE if the string is not found. The problem is that the code we’ve used in the previous two examples can produce some odd results: $str = “my little text string”; if (strpos($str, “text”)) { echo “Found ‘text’\n”; } else { echo “Did not find ‘text’\n”; } if (strpos($str, “my”)) { echo “Found ‘my’\n”; } else { echo “Did not find ‘my’\n”; } 120 Part II: Working with PHP This produces the following output: Found ‘text’ Did not find ‘my’ But we can see that ‘my’ clearly is inside ‘my little text string’. What gives? The problem is that in PHP, string positions start with 0. The string ‘my’ is at the beginning of ‘my little text string’, and so its position is 0, which is what strpos() returns. Just testing for zero or non-zero values isn’t good enough. We need to check explicitly for a return value of FALSE: if (strpos($str, “my”) !== FALSE) { echo “Found ‘my’\n”; } else { echo “Did not find ‘my’\n”; } This produces the correct result: Found ‘my’ You have to be careful to match your tests to the values you might be testing. Usually, that’s just a matter of — surprise! — checking the documentation. This is a good place to note that the functions you create in the course of your programming will often need to return a value indicating success or failure. You can make your functions do this by returning TRUE or FALSE. Take a look at this example that looks for http:// at the beginning of a string (a common task and one that illustrates the technique): //tests whether a variable starts with “http://” function url_test ($url) { if (strtolower(substr($url,0,7)) == “http://”) { return TRUE; } else { return FALSE; } } Chapter 5: Control Structures 121 $myurl = “http://www.theonion.com”; if (url_test ($myurl)) { echo “Thanks for entering a valid URL.”; } Comparison operators Table 5-1 lists the relatively few comparison operators in PHP. TABLE 5-1 PHP’S COMPARISON OPERATORS Symbol Operator Description == (2 equals signs) Equal to Determines if two quantities are equivalent. === (3 equals signs) Identical to Determines if two values have equivalent values and are of the same variable type. != Not equal Determines if two values are not equivalent. !== Not identical to Determines if two values are not equivalent, or not of the same variable type. > Greater than Determines if the value to the left of the symbol is greater than the one to the right. < Less than Determines if the value to the left of the symbol is less than the one to the right. >= Greater than or equal to Determines if the value to the left of the symbol is greater than or equal to the one on the right. <= Less than or equal to Determines if the value to the left of the symbol is less than or equal to the one on the right. 122 Part II: Working with PHP Logical operators In addition to comparison operators, you will be using logical operators in your scripts. Table 5-2 lists PHP’s logical operators. TABLE 5-2 PHP’S LOGICAL OPERATORS Symbol Example Description and if ($a ==0 and $b==1) Checks both conditions. && if ($a ==0 && $b==1) Same as the previous symbol, but has a higher precedence (see Note below). or if ($a ==0 or $b ==1) Determines if one or the other operand meets the condition. || if ($a ==0 || $b ==1) Same as the previous symbol, but has a higher precedence (see Note below). xor if ($a ==0 xor $b==1) This is known as exclusive or. It determines if one of the two operands is true but not both. If both of these conditions are true, the overall test will be false. ! if (!empty($a)) Determines if something is not the case. In this example the condition will be true if $a is not empty. The difference between && and and, and between || and or, is the order of precedence. PHP must determine which operators to compare first. It does this according to the list found at http://php.net/operators.Don’t forget, though,that parentheses override the order of precedence.The con- tents of inner parentheses get evaluated before those of outer parentheses. Complex if statements Using the operators in Table 5-1 and 5-2, you can create if statements that are a bit more complex than the basic one at the beginning of this chapter. Chapter 5: Control Structures 123 Here are a few quick examples: if ($var == 1 && $var2 <= 5 && !empty($var3)) { //do some stuff } Since this is a book dealing with MySQL databases, we’ll show some examples of if statements you can use when playing with database queries. To test if a select query returned any rows, you can use either of the following: $query = “select * from my_table”; $result = mysql_query($query)or die(mysql_error()); if (mysql_num_rows($result) > 0) { //do something here. } //this would also work $query = “select * from test.foo”; $result=mysql_query($query); if (!($row = mysql_fetch_assoc($result))) { echo “there were no rows to fetch, so the query must have returned no rows.”; } The following tests if an update query actually changed anything. A similar con- struct would work for delete statements. $query = “update mytable set col1=’my text’ where id = 1”; mysql_query($query) or die(mysql_error()); if (mysql_affected_rows() == 0) { echo “query did nothing”; } As is noted in Chapter 3, be careful to remember that the “equal to” operator is = in MySQL, but == in PHP. A common typo is to write if ($a = $b) in PHP. This assigns the value of $b to $a, and always tests as true, so it can be easy to miss. 124 Part II: Working with PHP if else statements If you’re clear on the previous sections, nothing here will surprise you. The else por- tion of an if else statement enables you to specify code that will be executed if the condition specified is false. The following code prints “it is not equal”: $a = 2; if ($a == 1) { echo “it’s equal”; } else { echo “it is not equal”; } if elseif statements You will often have to check a variable against more than one set of conditions. For instance, you might have a single page that will insert, edit, and delete records in a database. It is fairly typical to indicate which portion of the script you wish to run by assigning different values to a submit button in an HTML form. When the form is submitted, the value of the submit button can be checked against several elseif statements, as follows: if ($_POST[‘submit’] == “edit”) { // code for editing database } elseif ($_POST[‘submit’] == “update”) { //code for updating records } elseif ($_POST[‘submit’] == “delete”) { //code for deleting records } else { echo “I have no idea what I should be doing.”; } Chapter 5: Control Structures 125 elseif is technically not the same as else if. If you put that space between the words you will not get an error, but you could conceivably get different behavior. In practice, the two variations are equivalent. switch case The switch structure is an alternative to multiple if elses. It won’t work for everything, but in some situations switch will help you remove some ugly syntax. Choose a variable against which you wish to run a comparison. Continuing the example given in the discussion of if else, you may wish to execute differ- ent parts of a script based on the value passed by a submit button: switch ($_POST[‘submit’]) { case “insert”: // code to insert to database break; case “update”: //code to update database break; case “display”: //code to display break; default: echo “Unexpected value {$_POST[‘submit’]} for ‘submit’\n”; } Here the code tests against the value in $_POST[‘submit’]. If the variable is equal to “insert”, that portion of code is run. Note the use of break in the preceding code. If break is not included, the code will continue to run. For example, if $_POST[‘submit’] was equal to “update”, the following would run the code for both the update and display portions: switch ($_POST[‘submit’]) { case “insert”: // code to insert to database break; case “update”: //code to update database case “display”: 126 Part II: Working with PHP [...]... book contain a number of applications In the course of creating these applications, we made use of a little over 150 of PHP’s built-in functions So while thousands of built-in functions exist, you will probably make regular use of only a relatively small number 133 134 Part II: Working with PHP A pretty neat resource is the function table at http://www zugeschaut-und-mitgebaut.de/php/ Function Basics... practical, you will use a while loop to iterate through every row returned by a database query Since mysql_ fetch_assoc() will return false if there’s no row to be fetched, it works quite nicely with a while loop $query = “select fname, lname from people”; $result = mysql_ query($query) or die (mysql_ error()); while ($row = mysql_ fetch_assoc($result)) { echo $row[“fname”] , “ “ , $row[“lname”] , “... scripts you need to write But in the course of writing the large applications for this book, we didn’t need to use it once for The for loop takes three expressions ◆ The first is evaluated once before the second expression is tested ◆ The second argument is a condition that is evaluated each time through the loop; if the condition in the second argument tests false, the loop ends (or never begins if... something like alert(“you stink”); 137 138 Part II: Working with PHP The strip_tags() function will remove all HTML and PHP tags, except for those explicitly allowed in the second argument If you want to allow and tags, you can use this: strip_tags($str, “”) ADDSLASHES() This function is intended to work with your database insert and update queries string addslashes (string... while LOOPS Continuing with the subject of while loops and MySQL queries, you probably need a quick piece of code that prints out the results of any query For this, you can use a nested set of while loops The outer loop fetches each individual record from the database, and the inner one prints out the contents of each individual record: while($row = mysql_ fetch_assoc($result)) { while (list($key, $value)... the second character in a string on, you would use the following code: $str = substr ($str_var,1); However, the substr() function also has an optional third argument, which you can use to limit the size of the string that it returns A positive value counts forward from the position given in the second argument A negative value counts backwards from the end of the string So to get everything from the second. .. whether a variable is an array you can use the is_array() function, as in the following 135 136 Part II: Working with PHP if (is_array($var)) { //process array } Some functions will return a value if there is a value to be returned, and will return FALSE if there is no value to be returned A good example of this is the mysql_ fetch_array() function This function will grab rows from a result set returned... to grab When no more rows are to be had it returns FALSE As you saw in Chapter 5, this is very helpful for looping through all rows returned by a query $result = mysql_ query(“select * from my_table”) or die ( mysql_ error() ); while($row = mysql_ fetch_array($result)) { //process row } Finally, a function will occasionally return no value at all This is rare, as most functions at least return TRUE on... following example, we loop through the rows returned by a MySQL query, calling one function to do some initial processing and then calling a second function to do something with the first function’s results If either of those two functions fail, we want to stop the process right there and not continue with the rest of the rows while ($row = mysql_ fetch_assoc($result)) { $setup_result = setup($row);... get an error because the apostrophe is going to confuse MySQL You need to escape all occurrences of single quotes (‘), double quotes (“), and NULLs in the string For example: $str1 = “let’s see”; $str2 = “you know”; $str1 = addslashes($str1); $result = mysql_ query(“insert into show_stuff (stuff_desc, stuff_stuff) values(‘$str1’, ‘$str2’)”); echo mysql_ affected_rows(); So, given this potential problem, . Control Structures 1 23 Here are a few quick examples: if ($var == 1 && $var2 <= 5 && !empty($var3)) { //do some stuff } Since this is a book dealing with MySQL databases, we’ll. set col1=’my text’ where id = 1”; mysql_ query($query) or die (mysql_ error()); if (mysql_ affected_rows() == 0) { echo “query did nothing”; } As is noted in Chapter 3, be careful to remember that. mysql_ query($query)or die (mysql_ error()); if (mysql_ num_rows($result) > 0) { //do something here. } //this would also work $query = “select * from test.foo”; $result =mysql_ query($query); if (!($row = mysql_ fetch_assoc($result))) { echo