Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 1 – Part 1 Server Side Web Development (PHP & MySQL)

Similar presentations


Presentation on theme: "Chapter 1 – Part 1 Server Side Web Development (PHP & MySQL)"— Presentation transcript:

1 Chapter 1 – Part 1 Server Side Web Development (PHP & MySQL)

2 Introduction to PHP PHP Hypertext Preprocessor Personal Home Page
Server-side scripting language Used to develop dynamic web application Free and open source Can embed PHP scripts inside HTML PHP statements enclosed in <?php and ?> tags If short tags are enabled on the server, you can use <? and ?>

3 Introduction to PHP Browser will only get the php output code, if there is any Syntax is similar to C PHP doesn’t need the indenting, but it helps humans read the code.

4 Server-side Scripting
Runs the scripts on the web server enables the ability to highly customize the response based on the user's requirements, access rights, or queries into data stores.

5 Server-side scripting technologies
ASP JSP PHP Ruby on Rails

6 First PHP code

7 Processing PHP Files PHP pages cannot be directly viewed using a browser. Instead, you must deploy the php page in a web server and make request to the php page which resides in the web server using the browser. If the requested web page only contains pure HTML, web server directly sends the HTML page to the web browser If the requested web page contains a PHP code (<?php), web server sends the php code to the PHP processor (PHP Engine) and sends the processed HTML output to the browser

8

9

10 Displaying content on the web
Can use echo or print statements E.g. echo outputitem,outputitem,outputitem,...; outputitem can be a number, a string, or a variable echo “Hello”; echo 123; echo ‘Hello’,’World!’; echo Hello World!; // Not valid

11 Configuring the environment - Installing XAMPP
Download from windows.html Contains, MySQL PHP Apache phpMyAdmin It’s best to accept the default location - c:\xampp (on Windows Vista, 7, or 8, you cannot install in the Program Files folder because of a protection problem)

12 Configuring the environment - Installing XAMPP
Under Service Section, select the Install Apache as Service and the Install MySQL as Service check boxes. (causes them to start automatically when the computer starts) Then click install Enter localhost / in a browser For phpMyAdmin , Click the phpMyAdmin link in the Tools section toward the bottom of the left panel

13 Configuring the environment - Installing XAMPP

14 Configuring the environment - Installing XAMPP

15 XAMPP Control Panel Start -> All Programs -> Apache Friends -> XAMPP -> XAMPP Control Panel need to restart Apache whenever you make changes to your PHP configuration

16

17

18 Testing PHP Web space – a place where Apache looks for your scripts when you type localhost (c:\xampp\htdocs) can change the location of web space in the Apache configuration file. Open a notepad and type below code <html> <head><title>PHP test</title></head> <body> <?php phpinfo(); ?> </body> </html>

19 Testing PHP Save the file with the name test.php in your web space and localhost/test.php on the browser

20 Testing PHP Save the file with the name test.php in your web space and localhost/test.php on the browser

21 Configurations Configuring PHP
PHP looks for php.ini when it begins and uses the settings that it finds. If PHP can’t find the file, it uses a set of default settings c:\xampp\apache\bin\php.ini Need to restart after making changes

22 Configurations Configuring apache
configuration settings are stored in a file named httpd.conf. c:\xampp\apache\conf\httpd.conf can change some of Apache’s behavior with directives in the httpd.conf file (E.g. where Apache looks for web page files, what port number Apache listens on, etc) Configuring MySQL MySQL configuration file is c:\xampp\mysql\bin\my.cnf

23 Configurations 1. Stop both Apache and MySQL in the XAMPP Control Panel 2. Start the uninstall by choosing Start -> All Programs -> Apache Friends -> XAMPP -> Uninstall. 3. Move through the screens and answer the questions. can save any databases or web pages you have created by selecting the appropriate options 4. Start the installation procedure again from the beginning

24 PHP Basics

25 variables containers used to hold information
A variable has a name, and information is stored in the variable One of the most common uses for variables is to hold the information that a user types into a form

26 Naming a variable Identifier: All variable names have a dollar sign ($) in front of them. This tells PHP that it is a variable name. Beginning of name: Variable names must begin with a letter or an underscore. They cannot begin with a number. Acceptable length: Variable names can be any length. Acceptable characters: Variable names can include letters, numbers, and underscores only. Case sensitivity: Uppercase and lowercase letters are not the same.($firstname and $Firstname are not the same variable; i.e. case sensitive) Use meaningful names for variables

27 assigning values to variables
Must use = sign $age = 12; $price = 2.55; $number = -2; $name = “Jhone”; $name = “Bob”; // does not create a new variable. Replaces the value Jhone with Bob $name = “”; //The variable $age exists but doesn’t contain a value unset($age); // variable $age no longer exists.

28 Using variable variables
dynamic variable names . Mainly used with arrays and loops can name a variable with the value stored in another variable (one variable contains the name of another variable) $name_of_the_variable = “city”; $$name_of_the_variable = “Los Angeles”; $city = “Los Angeles”; // Final result $$ - means variable variable

29 Using variable variables
$Reno = ; $La = ; $cityname = “Reno”; echo “The size of $cityname is ${$cityname}”; $cityname = “La”; need to use curly braces around the variable name in the echo statement

30 Using variable variables
Without the curly brackets $Reno = ; $cityname = “Reno”; echo “The size of $cityname is $$cityname”; The size of Reno is $Reno

31 Displaying variable values
Can use : echo, print, print_r, var_dump

32 Using print and echo statements
$string1 = “Hello”; $string2 = “World!”;

33 Note Single quotes (‘ ‘): When you use single quotes, variable names are echoed as is. Double quotes (“ “): When you use double quotes, variable names are replaced by the variable values. Sometimes you need to enclose variable names in curly braces ({ }) to define the variable name. $pet = “bird”; echo “The $petcage has arrived.”; Above code will give you an error since it can’t find a variable called petcage

34 Note (Cont.) The above code will output “The birdcage has arrived.”
$pet = “bird”; echo “The {$pet}cage has arrived.”; The above code will output “The birdcage has arrived.” A variable keeps its information for the entire script (until the end of the page, if not defined inside a code block) – global scope

35 Using print_r PHP built-in function. E.g. $weekday = “Monday”;
print_r($weekday);

36 Using var_dump use to display a variable value and its data type
Mainly used in debugging (troubleshooting) E.g. $weekday = “Monday”; var_dump($weekday); o/p : string(6) “Monday”

37 PHP Constants Constant names are not preceded by a dollar sign
Same as variables Value never changes Constant names are not preceded by a dollar sign define(“constantname”,”constantvalue”); define(“COMPANY”, “Matrix”); echo COMPANY; // must not use quotes can store either a string or a number define (“AGE”, 29);

38 Data types in PHP PHP has 8 data types Integer: A whole number
Floating-point number (float): A numeric value with decimal digits String: A series of characters Boolean: A value that can be either true or false NULL: A value that represents no value Array: A group of values in one variable Object: A structure created with a class Resource: A reference that identifies a connection

39 Notes – Data types PHP determines the data type automatically (loosely typed) $var1 = 123; // an integer $var2 = “123”; // string PHP converts data types automatically Can use casting – changing the data type $var3 = “222”; $var4 = (int) $var3; can query the data type var_dump($var4); // int(222)

40 integers and floating-point numbers
PHP enables you to do arithmetic operations on numbers. $n1 = 1.5; $n2 = 2; $sum = $n1 + $n2;

41 Arithmetic operators + , - , *, /, % Note:
PHP does multiplication and division first, followed by addition and subtraction. If other considerations are equal, PHP goes from left to right. (can change the order parentheses) $result = * 4 + 1;

42 Formatting numbers In PHP if the number is 10.00, it’s displayed as 10
Can use sprintf(), number_format() methods to format numbers E.g. $newvariablename = sprintf(“%01.2f”, $oldvariablename); // adds 2 decimal points, return type is String $f_price = number_format($price,2); //adds commas to separate thousands and two decimal places

43 Strings in PHP a series of characters $string = “Hello World!”;
Single-quoted strings are stored literally — with the exception of \’, which is stored as an apostrophe. In double-quoted strings, variables and some special characters are evaluated before the string is stored.

44 Strings in PHP - Example
E.g. $month = 12; $result1 = “$month”; $result2 = ‘$month’; echo $result1; echo “<br />”; echo $result2; $string1 = “String in \ndouble quotes”; $string2 = ‘String in \nsingle quotes’; \t – inserts a tab

45 Strings in PHP - Example
$number = 10; $string1 = “There are ‘$number’ people in line.”; $string2 = ‘There are “$number” people waiting.’; echo $string1,”<br />\n”; echo $string2; OP: There are ‘10’ people in line. There are “$number” people waiting.

46 Joining Strings Can concatenate strings using dot .
$string1 = ‘Hello’; $string2 = ‘World!’; $string3 = $string1.$string2; $string4 = $string1.” “.$string2; echo $string3; echo $string4;

47 Joining Strings (Cont.)
can use .= to add characters to an existing string $stringall = “Hello”; $stringall .= “ World!”; echo $stringall;

48 Long strings in PHP - heredoc
A heredoc enables you to tell PHP where to start and end reading a string $varname = <<<ENDSTRING text ENDSTRING; // ENDSTRING can have any name

49 Boolean datatype $var1 = true; following values are evaluated as false The word false The integer 0 The floating-point number 0.0 An empty string A string with the value 0 An empty array An empty object The value NULL Note: If a variable contains a value , it is assigned the value true.

50 NULL datatype A variable with a NULL value contains no value
$var1 = NULL;

51 Conditional statements
Can use comparison operators Can compare both numbers and strings Strings are compared based on their ASCII code. = is assignment operator == is the comparison operator

52 Conditional statements

53 Testing variable content
isset($varname) # true if variable is set empty($varname) # true if value is 0 or is a string with no characters in it or is not set. is_int($number) # true if the value in $number is an integer is_null($var1) # true if, $var1 is equal to 0. is_numeric($string) #true if $string is a numeric string is_string($string) # true if $string is a string

54 Regular Expressions PHP provides support for Perl-compatible regular expressions Use to compare string with custom conditions E.g check whether a string includes a number Check whether a string ends with a certain character Patterns consist of literal characters and special characters Literal characters - normal characters (a-z) Special characters - have special meaning (*) Literal and special characters are combined to make patterns

55 Special Characters Used in Patterns

56

57 Examples A string is compared with the pattern, and if it matches, the comparison is true ^[A-Za-z].* Dear (BIT|Matrix) ^[0-9]{5}(\-[0-9]{4})?$

58 Joining multiple comparisons
Comparisons are connected by one of the following three words and: Both comparisons are true. or: One or both comparisons are true. xor: Only one of the comparisons is true.

59 Joining multiple comparisons
Comparisons are connected by one of the following three words and: Both comparisons are true. or: One or both comparisons are true. xor: Only one of the comparisons is true. Priority and xor or Can change the order using parentheses The || and && work in PHP as well || is checked before or, and the && is checked before and.

60

61 Using conditional statements
executes a block of statements only when certain conditions are true 2 types if switch

62 if statements if (condition) { block of statements } else if(condition) { } else { }

63 Note ‘if’ conditional statement contains only one statement, the curly braces are not needed E.g. if ($grade > 92) { $grade = “A”; } if ($grade > 92)

64 if ($score > 92 ) { $grade = “A”; $message = “Excellent
if ($score > 92 ) { $grade = “A”; $message = “Excellent!”; } elseif ($score <= 92 and $score > 83 ) { $grade = “B”; $message = “Good!”; } elseif ($score <= 83 and $score > 74 ) { $grade = “C”; $message = “Okay”; } elseif ($score <= 74 and $score > 62 ) { $grade = “D”; $message = “Uh oh!”; } else { $grade = “F”; $message = “Doom is upon you!”; } echo $message.”\n”; echo “Your grade is $grade\n”;

65 Nested if if ($custState == “ID”) { if ($ Add = “”) { $contactMethod = “letter”; } else { $contactMethod = “ ”; } $contactMethod = “none needed”;

66 Using switch statements
switch($variablename) { case value : block of statements; break; ... default: }

67 Note can use as many case sections as required.
default section is optional. (it’s customary to put the default section at the end, but it can go anywhere)

68 Loops Repeats something until a certain condition is met 3 types for
while do while

69 Using for loops based on a counter Each section can contain as many statements as needed, separated by commas for(startingvalue;endingcondition;increment) { block of statements; } E.g. for ($i=1;$i<=3;$i++) { echo “$i. Hello World!<br />”;

70 Nested loops example for($i=1;$i<=9;$i++) { echo “\nMultiply by $i \n”; for($j=1;$j<=9;$j++) { $result = $i * $j; echo “$i x $j = $result\n”; }

71 Complex for loops $t = 0; for ($i=0,$j=1;$t<=4;$i++,$j++) { $t = $i + $j; echo “$t<br />”; }

72 Using while loops continues repeating as long as certain conditions are true while(condition) { block of statements } Example

73 $fruit = array(“orange”, “apple”, “grape”); $testvar = “no”; $k = 0; while($testvar != “yes”){ if ($fruit[$k] == “apple” ) { $testvar = “yes”; echo “apple\n”; } else { echo “$fruit[$k] is not an apple\n”; } $k++;

74 Using do while loops continues repeating as long as certain conditions are true conditions are tested at the bottom of each loop do { block of statements } while(condition); Example

75 $fruit = array(“orange”, “apple”, “grape”); $testvar = “no”; $k = 0; do { if ($fruit[$k] == “apple”) { $testvar = “yes”; echo “apple\n”; } else { echo “$fruit[$k] is not an apple\n”; } $k++; } while($testvar != “yes”);

76 Avoiding infinite loops
Infinite loop is a loop that never ends A common mistake is using = instead of == E.g. while ($testvar = “yes”) ‘=‘ stores a value in a variable, while ‘==’ test whether two values are equal Another common mistake is that leaving out the increment statement ($k++) If you found an infinite loop; on a web page: The default timeout is 30 seconds, but the timeout period might have been changed. (can also click the Stop button on browser) On CLI: Press Ctrl+C ( Cmd+C on a Mac) Then figure out why the loop is repeating endlessly and fix it.

77 Breaking out of a loop Use to break out of a loop Two statements break: Breaks completely out of a loop and continue with the script statements after the loop. continue: Skips to the end of the loop where the condition is tested. If the condition tests positive, the script continues from the top of the loop. Note ‘break’ and ‘continue’ statements are usually used in conditional statements. ‘break’ is used most often in switch statements

78 Break statement example
$counter = 0; while($counter < 5) { $counter++; if($counter == 3) { echo “break\n”; break; } echo “Last line in loop:counter=$counter\n”; echo “First line after loop\n\n”;

79 Continue statement example
$counter = 0; while ( $counter < 5 ) { $counter++; if ( $counter == 3 ) { echo “continue\n”; continue; } echo “Last line in loop:counter=$counter\n”; echo “First line after loop\n”;

80 Note can use break statements for insurance against infinite loops. The following statements inside a loop can stop it at a reasonable point: $test4infinity++; if($test4infinity > 100) { break; } If you’re sure that your loop should never repeat more than 100 times, use these statements to stop the loop if it becomes endless

81 Functions in PHP a group of PHP statements that perform a specific task allows to reuse the same code in different locations E.g. print_name(); function print_name() { block of statements; return; //optional }

82 Functions in PHP (Cont.)
Local variable – a variable inside a function ( not available outside of the function) Can use global keyword to make local variable available out side of a function function format_name() { $first_name = “John”; $last_name = “Smith”; $name = $last_name.“ “.$first_name; } format_name(); echo “$name”;

83 Functions in PHP (Cont.)
if a variable is created outside the function, you can’t use it inside the function unless it’s global $first_name = “John”; $last_name = “Smith”; function format_name() { global $first_name, $last_name; $name = $last_name.”, “.$first_name; echo “$name”; } format_name();

84 Functions with parameters
Can pass values to a function by putting the values between the parentheses Must include the correct variable type function func_name($varname1, $varname2,..) { statements return; }

85 function compute_salestax($amount,$custState) { switch($custState) { case “OR” : $salestaxrate = 0; break; case “CA” : $salestaxrate = 1.0; default: $salestaxrate = .5; } $salestax = $amount * $salestaxrate; echo “$salestax<br />”;

86 Calling the function with the parameters
$amount = ; $custState = “CA”; compute_salestax($amount,$custState); can pass values directly (including computed values) compute_salestax(2000,”CA”); compute_salestax(2*1000,””); compute_salestax(2000,”C”.”A”); Must pass the parameters in the correct order and correct number of parameters

87 Passing the right number of values
A function is designed to expect a certain number of values to be passed to it. If you don’t send enough values, the function sets the missing one(s) to NULL. If you have your warning message level turned on, a warning message is displayed.

88 Passing values by reference
Normally, parameters are into the function by value (Copies are made for each parameter) E.g. function add_1($num1) { $num1 = $num1 + 1; } $num1 = 3; add_1($num1); echo $num1; // 3 When it is need to pass the original variable, parameter must be passed by reference into the function

89 Passing values by reference (Cont.)
When it is need to pass the original variable, parameter must be passed by reference into the function (mainly used when passing large values) E.g. function add_1(&$num1) { $num1 = $num1 + 1; } $num1 = 3; add_1($num1); echo $num1; // 4

90 Returning values from a function
When it is need to send back a value from a function (using return statement) E.g. function add_numbers($num1,$num2) { $total = $num1 + $num2; return $total; } $sum = add_numbers(5,6); echo $sum; // 4

91 Using built-in functions
many built-in functions in PHP PHP has already done all the work Must know the function name, parameters and operation of the built-in functions E.g. isset($varname); empty($varname);

92 Arrays Are complex variables
stores a group of values under a single variable name E.g. $cities[1] = “Colombo”; $cities[2] = “Kandy”; $cities[3] = “Galle”; Note : An array can be viewed as a list of key/value pairs. Each key/value pair is called an element. To get a particular value, you specify the key in the brackets.

93 Arrays (Cont.) Also can use words for keys E.g
$capitals[‘CO’] = “Colombo”; $capitals[‘KN’] = “Kandy”; $capitals[‘GL’] = “Galle”; The below code will automatically assign key indexes for the array $capitals[] = “Colombo”; $capitals[] = “Kandy”; $capitals[] = “Galle”;

94 Arrays (Cont.) Easy short cuts for creating arrays E.g.
$cities = array( “Colombo”,” Kandy”,” Galle”); $capitals = array( “CO” => “Colombo”, “KN” => “Kandy”, “GL” => “Galle” );

95 Viewing array elements
echo $capitals[‘CO’]; To view structure and values of an array print_r($capitals); var_dump($capitals);

96 Viewing array elements
echo “<pre>”; print_r($capitals); echo “</pre>”;

97 Removing values from an array
$cities[3] = “”; // sets the value to an empty string unset($cities[3]); // removes completely from the array

98 Sorting an array default order – create order
sort an array that has numbers as keys sort($cities); If you use sort() to sort an array with words as keys, the keys will be changed to numbers sort arrays that have words for keys, use the asort function asort($capitals);

99 sort arrays that have words for keys, use the asort function
default order – create order sort an array that has numbers as keys sort($cities); If you use sort() to sort an array with words as keys, the keys will be changed to numbers sort arrays that have words for keys, use the asort function asort($capitals);

100 Getting values from an array
$CAcapital = $capitals[‘CA’]; echo $CAcapital ; Note: If try to access an array element that doesn’t exist, a notice is displayed $Capital = $capitals[‘CX’]; Notice: Undefined index: CX in c:\test.php on line 6 @$CAcapital = $capitals[‘CAx’]; // Can prevent the notice

101 Getting values from an array (Cont.)
Can use ‘list’ statement to get several values from an array at once E.g. $flowerInfo = array (“Rose”, “red”, 12.00); list($firstvalue,$secondvalue) = $flowerInfo; echo $firstvalue,”<br />”; echo $secondvalue,”<br />”; can retrieve all the values from an array with words as keys by using extract. (Each value is copied into a variable named for the key) E.g

102 Getting values from an array (Cont.)
$flowerInfo = array (“variety”=>”Rose”, “color”=>”red”, “cost”=>12.00); extract($flowerInfo); echo “variety is $variety; color is $color; cost is $cost”;

103 Array Iteration (traversing.)
Walking through an array E.g. echo each value store each value in the database add 6 to each value in the array 2 types Manually: Move a pointer from one array value to another. Using foreach: Automatically walk through the array, from beginning to end, one value at a time.

104 Manually walking through an array
Can use a pointer current($arrayname): Refers to the value currently under the pointer; doesn’t move the pointer. next($arrayname): Moves the pointer to the value after the current value. previous($arrayname): Moves the pointer to the value before the current pointer location. end($arrayname): Moves the pointer to the last value in the array. reset($arrayname): Moves the pointer to the first value in the array.

105 Manually walking through an array
E.g $cities = array(“Colombo”, ”Kandy”, ”Galle”); $value = current($capitals); echo “$value<br />”; $value = next($capitals);

106 Manually walking through an array
To reset the pointer, use; reset($capitals);

107 Foreach walks through the array one value at a time
foreach($arrayname as $keyname => $valuename) { block of statements; } foreach($arrayname => $valuename); E.g. $capitals = array(“CA” => “Sacramento”, “TX” => “Austin”, “OR” => “Salem” ); ksort($capitals); foreach( $capitals as $state => $city ) { echo “$city, $state<br />”;

108 Extra Notes

109 Comments in php 3 types // Single line /* Multi line */ # single line

110 Variables in PHP Loosely typed All variables in PHP starts with a dollar ($) sign. $name $_code_ptr $first_name $log99 The starting letter of a variable must be a letter or an underscore. PHP variables are case sensitive

111 Variables scopes in PHP
local global static parameter <?php $a = 5; // global scope function myTest() { echo $a; // local scope }  myTest(); ?>

112 Variables scopes in PHP
<?php $a = 5; // global scope function myTest() { echo $a; // local scope } myTest(); ?>

113 String variables in PHP
<?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; echo strlen("Hello world!"); echo strpos("Hello world!","world"); ?>

114 Arrays in PHP An array in PHP is a collection of key/value pairs, which maps keys (indexes) to values. Array indexes can be either integers or strings whereas values can be of any type.

115 Arrays in PHP An array in PHP is a collection of key/value pairs, which maps keys (indexes) to values. Array indexes can be either integers or strings whereas values can be of any type.

116 Multidimensional Arrays

117 Operators x === y – Identical x !== y - Not Identical a .= b a = a . B
x <> y - Not equal, same as x != y

118 Logical Operators

119 String Operators

120 Control Structures Refer BIT notes

121 For and Foreach

122 Functions in PHP A function in PHP is a set of statements that performs a specific task. A function will be executed by an event or by a call to that function. E.g. $length = strlen(“UCSC"); /* strlen is a standard PHP function that returns the length of a string*/ A function can be built-in or user-defined PHP supports over 140 categories of built-in functions and many of these are available within the PHP core.

123 Built-in Functions print() include() header() print “Hello World”;
print(“My first PHP script”); include “header.php”; header(“Location:

124 User-defined Functions

125

126 Built-in Functions print() include() header() print “Hello World”;
print(“My first PHP script”); include “header.php”; header(“Location:

127 PHP Sessions HTTP is a stateless protocol
allows an application to store information for the current “session” A session is identified by a unique id PHP creates a session ID that is an MD5 hash of the remote IP address, the current time, and some extra randomness represented in a hexadecimal string.

128 Starting and Destroying
session_start(); session_destroy(); $_SESSION // global array, which stores the session data $_SESSION['userid'] = ‘Caldera'; unset($_SESSION['userid']); session_id() ini_set() // executes after the session start

129 PHP Objects An object is a collection of properties (data) and methods (functions). A class is a template for an object and describes what methods and properties an object of this type will have E.g. class <class_name> { // List of methods // List of properties }

130 Cont. Creating an object $newObject = new myClass();
Then, the constructor will be called [ __construct() ]

131

132 Access modifiers Public Private protected

133 Processing form data $_GET to possess data from a form that uses the GET method $_POST to possess data from a form that uses the POST Method $_REQUEST to possess data from a form that uses either method (GET or POST) E.g

134 PHP MySQL Functions <?php $host = ‘localhost’; $user = “root”; $pass = “123”; $conn = mysql_connect($ host , $user, $pass) or die(‘’); mysql_select_db(‘Student’) or die(‘’); ?>

135 MySQL functions mysql_query()
sends a query to the database and returns a result object mysql_fetch_array() fetch the resulting rows as an array. Once fetched a row, field data can be accessed using their name or the index. E.G $row = mysql_fetch_array($result, MYSQL_ASSOC); echo $row[‘username’];

136 PHP Errors and Troubleshooting
Syntax or parse errors Fatal errors Warnings Notices Logical errors Environmental errors Runtime errors Core errors

137 PHP Errors and Troubleshooting
Syntax or parse errors identified when a PHP file is processed, before the PHP interpreter starts executing it E.g. missing semicolons (;), parenthesis (), dollar ($) signs, curly brackets {}, misspelled keywords Fatal errors interpreter simply stops running the code occur when there is a severe problem with the content of code E.g. calling an undefined function

138 PHP Errors and Troubleshooting
Warnings prevent the correct execution of the program but not cause it to halt. E.g. invalid regular expressions or missing files Logical or semantic errors faults in program design i.e. in the order of instructions may cause a program to respond incorrectly to the user’s request or to crash completely Runtime errors occur during execution of the code E.g. disk or network operations or database calls.

139 Error reporting error_reporting() function controls the level of errors reported at runtime. E_ALL - For all errors E_PARSE - For parse errors E_ERROR - For Fatal errors E_WARNING - Warnings E_NOTICE - For notices

140 Error reporting E.g. <?php //Disable error reporting error_reporting(0); //Report runtime errors error_reporting(E_ERROR | E_WARNING | E_PARSE); //Report all errors error_reporting(E_ALL); ?>


Download ppt "Chapter 1 – Part 1 Server Side Web Development (PHP & MySQL)"

Similar presentations


Ads by Google