0% found this document useful (0 votes)
17 views

PHP Mod 3

Uploaded by

Drisya Dinesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
17 views

PHP Mod 3

Uploaded by

Drisya Dinesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 31
Web Pr UNIT 3 INTRODUCTION TO PHP PHP stands for “PHP: Hypertext Preprocessor. PHP is 8 Open sou general-purpose scripting language that is suited for web develop, and can be embedded into HTML code. Itis a server side scripting tools. its code is similar to Java, Cand Perl. The main objective of PHP isto devel dynamic web pages at ease. PHP was originally created by Rasmus eri in 1994 but it is now developed by The PHP Group. PHP is a powerful tool for making dynamic and interactive Web page PHP stands for Hypertext Pre-processor. PHP is a server side Scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. PHP code is inserted inside HTML code and when the user requests for a PHP web page, i is interpreted and executed on the web server. lo Process the PHP code on the web server, a PHP interpreter has tote installed on the web server. After execution of the PHP code in the wed server, an HTML page is created, which is sent to the client browser. One of the strongest and most significant features in PHP is its suppot for database programming, The most common database used with PHP: Mysql. oe tere PHP interpreters available for all operating systems. Linux platfor commonly use LAMP. (Linux, Apache, MySQL and PHP) server softwae which is freely downloadable. LAMP uses Linux as the server opersts System, Apache as the web server, MySQlL as the database and PH? <*rver side scripting. Windows operating systems use WAMP sé" Software which is alsoavailable for free download. PHP web Pres! 135 ranuning USINS se wer side scripting a server-side scripting is a method of designing websites $0 that the rocess or userreduest is run on the originating server, Server-side scripts wide an interface to the user and are used to limit access to Proprietan ad help keep control of the script source code. Below is an asle dataa F i i nt-side scripts vs. server-side scripts. of cle the server-side environment that runs a scripting language is a web ener Auser’s request is fulfilled by running a script directly on the web server to generate dynamic HTML pages. This HTML is then sent to the dlient browser. It is usually used to provide interactive web sites that interface to databases or other data stores on the server, Server-side scripting as it relates to web pages usually refers to PHP code that is executed on the web server before the data is passed to the user’s browser. In the case of PHP, all PHP code is executed server-side and no PHP code ever reaches the user. After the PHP code is executed, the information it outputs is embedded in the HTML, which is sent to the viewer's web browser. The result of the PHP code is there because it is embedded in the HTML on the server before the web page is delivered to the browser. Thisis different from client-side scripting where scripts are run by the Viewing web browser, usually in JavaScript. The primary advantage to Server-side scripting is the ability to highly customize the response based onthe user's requirements, access rights, or queries into data stores. Ascript is a program or sequence of instructions that is interpreted OF carried out by another program rather than by computer processol atabase that reside on residing at pared toa i Server side scripting is used to connect to the di e Web server, Server side scripting can access the file system © Web server. Response from a server-side is slower a com| cli lent-side script because the scripts are processed 0” a computer. e remote rE Web Programming Using Pip The webserver is ] acre | > |e f [arts = Internet | < t gt = ss a as i Role of web server software a Hosting websites refers to placing websites on web sony ay a s play a si them into access by people over internet.web set ut Y a significant | ot role in web hosting services as they form the key elements. ‘The term web server is often used for referringto the server computer | gif that hosts websites. It is also used to refer to a web server software thatis | il installed in a server computer in order to make it a web server. It is also ket used to refer to a web server software that is installed in a server computer | 4, in order to make it a web server. ‘Aweb server enables us to deliver web pages or services like e-mail, blog, etc. to users on the Internet. A web server consists of a server computer that runs a server operating system and a web server software installed on it for providing services like www, e-mail, etc. over the Internet. | * Following are a few functions performed by web servers in hosting. * Stores and secures website: in web hosting services, web servel ty cell websites data and secures it from unauthorized uses | when it is properly configured, ty *° Provides iii web database access: a webservers responsibility st? } * ee access to websites that are hosted. Web hosting servi? ro} pao aa some Web servers that are used in variable ways"? Mferent web hosting services such as backend databas® Web Programming Us, ing Dy i e ebpage your webpages in the folio, i wn fol ng S. poe der; that contains create vou path laces? computer? opt folder-> lampp-> htdocs.» > click places E ; ae te your folder in this htdocs folde! © Creal ve your Php programmes or webpages in this folde, Then s@ ° webpages in Lamp! ywser : p webserver. 3, viewing ena web bro' 2 ; ae the url like: nttp://localhost//yourfolder/filename. php ° Eg: nitp:/flocalnost/bvmcollege/index:PhP nttp:/flocalhost/bvmcollege/courses-htm| Let's continue with php pHP documents end with the extension .php. When a web seryer encounters this extension in a requested file, it automatically passesitts the PHP processor. A PHP document will output only HTML. To provethis you can take any normal HTML document such as an index.html file and save it as index.php, and it will display identically to the original. For inserting php commands use a new tag. Inside ths tag you can insert your php commands. A simple. ‘hello world’ php progran shows below. php comments Acomi = mentin PHP codes a line that is not read as part of the pros Its only pury is aoe Pose is to be read by someone who is editing the cod® types of comments, Thay are: 1. Single line comment For single line cama comment use // or # at the beginning of the lt ing Using PHP f (ay isasingle-line comment te | | oe js also. [2 L— ult e rhe multiple line PHP comment begins with “ /* « for example ae ‘erphp o’welcome”; single-line comment and ends with “*/ ee See eee a t This is a multiple-lines comment that spans over multiple lines. / > [2S Ss es ea Rr eee Ee ae echo and print echo and print statements to display the output in a web browser. Echo statement The echo statement can display anything that can be displayed to the browser, such as string, numbers, variables values, the results of ‘expressions etc. Eample 1: This is a simple heading." Web Programmin, STAMIMNINE Ug Pp 140 grample p< | $a= 2 | gb = 2.55 gcc $a + $b | print(*$a+ 90 = ee | a ae int statement Hes the print statement to display output to the br ho statement .Like echo the print is also a language So you can also use it without parenthecs, You can also use Itan alternative to echo st construct not a real function. like: print or print(). Both echo and print statement works exactly the same way exces that the print statement can only output one string, and always returns1, That’s why the echo statement considered marginally faster thay the print statement since it doesn’t return any value. For example Stxt = “Hello World!”; Snum = 123456789; print $txt; print “
”; print $num; Difference between echo and print statement In PHP, echo i: Echo Print P, echo is not a functi as language conerce, > (unction But a |in PHP, print is not a really fre but a language construct. Howevel lt behaves like a function in tht itcan accept multiple expressions, returns a value. Itis faster th; sions an i Itcannot accept multiple expre Print as i il Feturn any value, does not | itis stower than echo as itreu”™ value. ~~ = NCEA GG Sie = WS a agrvrening U ra Fement used cam the | Itis aoa sta = in pu and can pereee pe the | display the out, cad which is used to. erent ages echo, OF without the | parentheses ante used with the | [ees S10 —_—_—_—_——__ aenthese rin }or wut the | ule Sing separated |i cannot pas mule aumens 1 an ae ne uments 1 oe always returns the value i, x pois aster than print [itis ae ns thie Valle 10 | variables variables are named locations to store data. | ji snststarts with dollar(S) symbol. For example. eee 5 §vars a Rules for PHP variables: Variable starts with the $ sign, followed by the name of the variable. + Variable name cannot start with a number. aletter or the underscore character. * Variable name must start with * Variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _). * Variable names are case-sensitive that Data Types ure Values assigned to a PHP variable may be agye ne ImPle string and numeric types to more complex d Ysand objects. want? be, ata tis $x and $X are different. of different data types fata types like es; Integer, Floating point ree and NUL Supports total eight primitive data tYP “These r Float, String, Booleans, Array, Object, resou es are used to construct variables. 2 [Datatype — — string Integer Eee Float (double) ~ is a sequence of A Str ne "Helloworld” a string can be any text i uotes. ict re al numbers 8 | considered as integer oe type. It includes en e negative or positive numbers. Fitis a number with decimal part. Web Programming Using ip [Example —~_ | Boolean | ‘A Boolean represents two possible states( TRUE or FALSE). Booleans are often used in conditional testing. $x = true; Array An array stores multiple values in a single variable. "; > Object Objects are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class. NULL The special NULL value i: is used to represent empty Variables in PHP. When a variable is created without: a, itis automaticallyass; a value of null, ponies Resource Aresource holding a ;apocclalvariable, Teference to an —— |e crepe ia P/E: (aa IST eal eS ming Using PHP pgreoi"s Pa operators orators an ds(variad | mrthmetic Operators rison Operators are symbols that are used to c 9 perform o; perations Jes) and values. Different types of aperat o erators in php are; « compal « Logical(or Relational)Operators . Assignment Operators + conditional(or ternary) srithmetiC Operators carithmé addition, ‘etic operators are used to perform mathematical calculations like subtraction, multiplication, division and modulus. pete Operation Prarie } + _| Addition ae i 2 Subtraction Sa-Sb < multiplication $a*$b | L Division $a/Sb | % Modulus $a%Sb ] en Increment operator, increases integer value | by one Satt+ = Decrement operator, decreases integer value | by one tail Sa | Sample: program to perform arithmetic operations us Fecho $a $bi | echoga* sb? | echo $a/ $bi echo $a% $b; echo Sati echo $a—1 > | C/N eee 2s a Comparison Operators Comparisonoperato variables. i.e. to compare rs are used to find the relation between ty the values of two variables in the program, Sues Example Description S Sx >6y $x is greater than $y z Sx ee Operators | 0) Print’Sa is positive”, else i Print”’Sa is negative”. ?> z ig € 3 | CRUE: Sy =e ing PHP rons vs ie erators va Je A holds 10 and vari en holds 10 and variable B holds 20 then: F a Description [example ope —ajied Logical AND operator. if both the |(Aand ave | ands are true then condition becomes ES | an | ope! | _|os-00t__—__ eee | —T called Logical OR Operator. If any of the two Saal bea or | operands a einonizerostheokcondition|\.sgu o aumeal becomes true. i Called Logical AND operator. If both the | —— operands are non zero then condition | (A && B) is true.| becomes true. | Called Logical OR Operator. If any of the two (|| 8) istrue. operands are non zero then condition | becomes true. | Called Logical NOT Operator. Use to reverses | | the logical state of its operand. Ifa condition MA 8&8) is false. i is true then Logical NOT operator will make false. The operatorsand and or have a lower precedence, so in some cases, you may need extra parentheses to force the required precedence. Assignment Operators ‘These operators are used to assign values to variables. Operator Example Equivalent to | i $x=5 $x=5 Sxt= 5, $x = xt 5 $x %= 5 ‘or to append one riod (.) operat : tne way to do this is a5 follows: eee | Note: ses ks String concatenation uses the '8 of characters to another. The S| Web Programmi sea ee » ie 1 gmses «“ messages.”; echo you have eal assuming that the varial suming Oe from this line of code will be: You hav ble Smsgs is set to the value 5, the a Puy eS messages ernary) ore operator called conditional operator. This n expression for atrue OF false value and then execute one oi statements depending upon the resultof the Valuation ional operator has this syntax: conditional (oF t There is one m evaluates the two Bi The conditis a Operator| [Example oe Conditional Expression | If Condition is true ? Then value. as : Otherwise value Y | Example ; Branching statements The special types of PHP statements used for making decisions are called decision making statements or branching statements. Branching statements are the set of commands used to perform different actions based on different conditions. The following are the different types ot branching statements. 1, If statement 2. If -else statement 3. Else if statement 4. Switch statement If statement If stat ément allows you control the execution of statements! statemen’ it can only executes one or more php statement(s) only whet i conditional expression j. ele n Is evaluated as true. The general syntax if (conditional expression) statement(s); } ing PHP moins US ost we! (588°? 7 { grou are eile For voting ed ea ESS a else statement L : 1s want to execute some code if a condition is true and another cgeitaconaltion is false, use the if....else statement. General syntax is: Uy Frpfenditional expression) q ey statement(s); | | | seit (conditional expression) | Sa statement(s); i a For example $dedate(“D"); if($d=="Fri”) echo “Have a nice weekend!”; else & echo “Have a nice day!" Else if statement sare true ifyou want to execute some code if one of several condition: the elseif statement. General syntax is: if (condition_1) { statement_1 he {condition_2) jefaullt statements” fpreaki) ee example $n=5) switch (90) { case $n? echo “This is positive”; break; case $n: echo “This is negative”; break; case $n: echo “This is zero”; break; default: echo “enter a number !!!”; Looping statements are used to repeat the same block of code agiven Funber of times, or until a certain condition is met. Php has four types ot Fo s.In addition, you can use the Break and Continue statements within Ping statements, * The While Loop ' : The Do... While Loop The For Loop “The Foreach Loop Bi "eak and Continue Statements anmang using PHP rl pres " mple_ {"; | | Satti } while (a < $b); | > ‘Output | 3isless than 7 | gisless than 7 | Sisless than 7 Gis less than 7 | Difference Between while and do...while Loop The while loop differs from the do-while loop in one important way ith awhile loop, the condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false, the loop will never be executed. With a do-while loop, on the other hand, the loop will always be eecuted once, even if the conditional expression is false, because the condition is evaluated at the end of the loop iteration rather than the beginning. For loop mes. PHP for loops This loop is f the script. | @recutes a piece of code a specific number of tin ae a block of code for a specified number of times. ferred when you are sure about the number of iterations of Sintay ‘ounter) e (initial counter; test counter; increment ¢ hee Of code to be executed; Web Prograrmting Using Fs He . forloop has Initial coun! eters a eas to initialize the loop counter value, ters re to evaluate each and every loop iteration, Le erreurs otherwise it will stop. true, the counter will be used to increment or decrement the a Sat+,Sb-). Hig Test col increment counter counter value (2.8: ae ”;// will echo numbers till 5 from 9 echo ; | ?> Output The number is: 0 The number is: 4 The number is: 5 Foreach loop The foreach construct provides an easy way to iterate over artals foreach works only on arrays and objects, and willissue an error when a tty to use it on a variable with a different data type or an uninitl variable. There are two syntaxes: foreach (array_variable as statement } Sarray_value){ foreach (array_variable as statement Skey => Sarray_value){ t ing using PHP wt a form loops over the array given by nef value of the current elements as, re Signed to Sai | rray_val eel 3784 oT ESE by one (50 on the nest tented pein king at the next element), When foreach fir starts eet pe 00! - ‘ vol aera array pointer is automatically reset to the first element of the ein yah the se* ape he 4 HERE, sgrray_variable” is the array variable to be looped through 153 Y array_ variable, On each cond form will additionally assign the cur 5 rent ele ¥ riable on each iteration. Ment's key to “$onray_value “ is the temporary variable that holds the current array zm values. How it works Inevery iteration, value of current array element will be assigned to Saray value and the array pointer is moved by one. The process repeats unt the last array element is reached. fiumple: php Scars = array(“Skoda”, “Nissan”, “Toyota”, “Suzuki"); foreach (Scars as Sbrand) echo “Sbrand
"; } ee ae Output Skoda Nissan Toyota Suzuki stored in an mye above example, four different brand Te . ate as "but, "lable Scars, For each loop matches eve use for loop We Geet frer satisfying which the . For this reason rs in our lop me counte! viously occupies some we use SO! which ob memory. forloo know already | Jor loop is used if we know already that how many times the script should be run oa a But while using foreach |00p ve | oop, ___________| In the case of foreach loop, ye) Web Pr ro gramming Uy, sing by don’t have to think about i | counter, In case of foreach jgy there is no extra memory requ for the counters also, Because y, don’t have any counter inforeag} loop. don’t have any idea about the number of iteration. | for statement can be used in any program. That is for works with a normal variable. foreach loop is used to iterate only arrays and objects Arrays Array is a collection a collection of values of same type under: aE common name. If we want to store the names 50 students; then we hat to use 50 variables. It is very complex to maintain 50 variables. The problems of handling bulk amount of variables by using arrays. There are three types of arrays in PHP are: 1, Numeric arrays or indexed arrays. 2. Associative arrays 3. Multidimensional arrays Some arrays are r of eferenced (oat Sse the sie alphanumeric identifiers, by numeric indices; ot Numeric arrays Numeric array uses evel | elementin the array is id humbers as access keys (index). Each an ie ‘dentified by this access key or index. By de!" value of the ind aes lex is start wi ‘modify its valu if h e Below is the zero. This access key is used tO Syntax for creating numeric array '"P Web Programming Using py ip ociative arrays Ass ffer from numericarrayin the sense that associ, jative array di eerie names for id keys. In an associative array, they, jes A : an be arbitrary and user defined strings. Below icy, ssociative array in php. arrays use gssigned to values © syntax for creating @: {” value); > Here, “Svariable_name...” is the array name, “['key_name’)” is the alue” is the value assigned to the array, access index of the element and “vi Sometimes it’s better to use the index name instead of index number For example if you want to save three students’ names and numbers so your best option will be to use each student's name as index value for the array and his numbers as the values. "; =employee(0}(0].” Designatio echo “er “gemployee(OI[2}."
"; a gemploye employee name : (a)(a).” salary: « Gemployee(2I{0].” Designation : « &employee(2][2].”
”; ae ae echo «gemployee! “employee name : ecie salary : «gemployee(2]{2).” Scars = array( array(“Honda Accord”, “V6”, 830000), array(“Toyota Camry”, “LE”, 924000), array(“Nissan Altima”, “V1”, 890000), ) for($i=0;Si$value) { Sct; echo $key."="$value; ' if(Sc”. } > Viewing Array Structure and Value: You can see the str ‘ statements — var s Pi and values of any array by using one alt Bives somewhat less viformatee The print_r() statement, howe | » Consider the following example nett Using PHP apne. jioetine arra’ Tae gaitles* array(“London’, “Paris”, “New York | rk) \ pysay the cities 2772 | | inn ils = aes ars output Se ee ray ( (ol => London [1] => Pai e ris [2] => New York) qhisoutput shows tht e key and the value for each elem ent in the array . following example shows the use of var_d shows thelse/ofivar-dumet) php. [Define array | seties = array(“London’, “Paris”, “NewYork’); , rk); // Display the cities array var_dump(Scities); > Output : array(3) { (0]=> stri “ ao ae => string(6) “London [J string(5) “Pari is” (2]=> string(8) This out, ut put shows the data type of each element, such as @ string of Scharact ters, in addition to the key and value. Ioortant array functions ind manipulate the access @ below. PHP Provi ‘i ides various array functions t nections are given Semen Its of array, The important PHP array fu 1 ~ PHP array() function you to Pup array i y() function creates and returns an array, tt allows jonal arrayS- i ve eat eindey Xe d, associative and multidimens! pxomple_ Output: 3 3. is_array function The is_array function is used to determine if a variable is an array «wir. Jones”, “Mr. Banda’, “Mrs. Smith’); Output: 1 4. sort() This function is used to sort arrays by the values. If the values alphanumeric, i fs ;, it sorts - it sorts them in seat on lphabetical order. Ifthe values a°@"™ add new numeric keys, ler. It removes the existing access Keys bby, SS Ais using PHP. tS oa os W" = s Ses 163 | gal?) | Sresul | pintsresulth t= sizeof(Sa)s % Da sis will produce the following result ” 3 0. array_unique() trearray_unique() function removes duplicate values from an array eat —— sinput = array(“a” => “green”, “red’, “b” => “green’, “blue’, “red”); Sresult = array_unique(Sinput); print_r(Sresult); ire acre | This will produce the following result “ Array ( a] => green [0] => red [1] => blue) 41, array_sum() It calculates the sum of values in an array and returns the sum of ‘alues in an array as an integer or float. 3.4): This wilh produce the following result “ “um{ba) = 20 Sum(ab) = 6.9

You might also like