Basic php


Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Basic php

  1. 1. Basic Php Pengaturcaraan PHP Pengaturcaraan PHPWhat Is PHP?PHP originally stood for Personal Home Page as it was created in 1994 byRasmus Lerdorf to track the visitors to his online résumé. As itsusefulness and capabilities grew (and as it started being used in moreprofessional situations), it came to mean "PHP: Hypertext Preprocessor." 1
  2. 2. Pengaturcaraan PHPPHP is a server-side, cross-platform technology Its cross-platform naturemeans that PHP runs on most operating systems, including Windows, Unix(and its many variants), and Macintosh Pengaturcaraan PHPExample Server-Side Programming PHP, ASP, JSP, Servlet, Perl, RXML, Python, CFML, Tcl, Miva, iHTML, RADpage, SSI, iPerFrom, ePerl, Ruby Client-Side Programming HTML, Javascript, VBscript, Java Applet, CSS, DHTML 2
  3. 3. Pengaturcaraan PHP PHP is a scripting language, as opposed to a programming language: PHP was designed to write Web scripts, not stand-alone applications. The scripts run only after an event occurs for example, when a user submits a form or goes to a URL. Pengaturcaraan PHPWhy Use PHP?PHP is better, faster, and easier to learnThan the alternatives.What you get with PHP is excellentperformance, A tight integration with nearlyevery database available, stability, portability,and a nearly limitless feature set due to itsextendibility. All of this comes at no cost(PHP is open source) andwith a very manageable learning curve. 3
  4. 4. Pengaturcaraan PHPFinally, the proof is in the pudding: PHP has seen an exponential growthin use since its inception, overtaking ASP as the most popular scriptinglanguage being used today. Its the most requested module for Apache(the most-used Web server), and by the time you read this, PHP will beon about 20 million domains. Pengaturcaraan PHP How PHP Works PHP is a server-side language. This means that the code you write in PHP resides on a host computer called a server. The server sends Web pages to the requesting visitors (you, the client, with your Web browser). When a visitor goes to a Web site written in PHP, the server reads the PHP code and then processes it according to its scripted directions. The PHP code tells the server to send the appropriate data — HTML code — to the Web browser, which treats the received code as it would a standard HTML page. 4
  5. 5. Pengaturcaraan PHPThis differs from a static HTML site where, when a request is made,the server merely sends the HTML data to the Web browser and thereis no server-side interpretation occurring. Hence, to the end userand the Web browser there is no perceptible difference between whathome.html and home.php may look like, but how that pages content wascreated will be significantly different. Basic Syntax Pengaturcaraan PHP 5
  6. 6. Pengaturcaraan PHPPHP is an HTML-embedded scriptinglanguage. What HTML-embeddedmeans is that you can intermingle PHPand HTML code within the samescript.Pengaturcaraan PHPTo place PHP code within this document,you surround the code with PHP tags,either the formal and preferred or theinformal.Anything placed within these PHP tagswill be treated by the Web server as PHP(meaning the PHP interpreter willprocess the code; text outside of thePHP tags is immediately sent to theWeb browser). 6
  7. 7. Pengaturcaraan PHP A final consideration for your PHP scripts is that the file must use the proper extension. The extension tells the server to treat the script as a PHP page. Most Web servers will use .html or .htm for standard HTML pages, and normally, .php is preferred for your PHP scripts. Pengaturcaraan PHPCreating a Basic PHP ScriptThis first PHP script doesnt do anything,per se, but it will demonstrate the syntaxto be used.Step 1Create a new document in your texteditor.It generally does not matter what texteditor you use, be it BBEdit on theMacintosh, the very basic Notepad ormore advanced Dreamweaver onWindows, or vi on Linux. 7
  8. 8. Pengaturcaraan PHPPengaturcaraan PHP 8
  9. 9. Pengaturcaraan PHPPengaturcaraan PHP 9
  10. 10. Sending Data Pengaturcaraan PHP Pengaturcaraan PHPTo build dynamic Web sites with PHP, you must know how to send datato the Web browser. PHP has a number of built-in functions for thispurpose, the most common being echo() and print(). Either single or double quotation marks will work with either function. Also note that in PHP all statements (a line of executed code, in laymans terms) must end with a semicolon. 10
  11. 11. Pengaturcaraan PHPLooking for an EscapeAs you might discover, one ofthe complications with sendingdata to the Web involves printingsingle and double quotationmarks. Either of the following willcause errors.Pengaturcaraan PHPThere are two solutions to this problem. First, use singlequotation marks when printing a double quotation mark andvice versa. 11
  12. 12. Pengaturcaraan PHPOr, you can escape the problematic character by preceding it witha backslash.Pengaturcaraan PHP 12
  13. 13. Pengaturcaraan PHPPengaturcaraan PHPIf you see an entirely blank page, this is probably for one of two reasons:-There is a problem with your HTML. Test this by viewing the sourceof your page and looking for HTML problems there.- An error occurred, but display_errors is turned off in your PHPconfiguration, so nothing is shown. Review your PHP configurationdocumentation so that you can turn display_errors back on. 13
  14. 14. Pengaturcaraan PHPSending HTML codeYou can also use echo() and print() to send HTML code to the Web browser:echo <b>Hello, <font size="+2" >world</font>!</b>;Sending multiple chunks of dataWith echo() but not print(), you can send multiple, separate chunks of data tothe Web browser using commas:echo Hello, , world! ;Printing over multiple linesEcho() and print() can both be used to print text over multiple lines. Understanding PHP, HTML, and White Space Pengaturcaraan PHP 14
  15. 15. Pengaturcaraan PHP With this in mind, there are essentially three areas where you can affect spacing: in your PHP scripts, in your HTML source, and in the rendered Web page. The extra spaces, tabs, and blank lines you create are generically known as white space.Pengaturcaraan PHPCreating White SpaceTo alter the spacing of the finishedWeb page, use the HTML tags <br/>(line break, <br> in older HTMLstandards) and <p></p>(paragraph).To alter the spacing of the HTMLsource created with PHP, you can useecho() or print() over the course ofseveral lines or use the newlinecharacter (n) within doublequotation marks. 15
  16. 16. Writing CommentsPengaturcaraan PHPPengaturcaraan PHP Writing the executed PHP code itself is only a part of the programming process. A secondary but still crucial aspect to dynamic Web site development involves documenting your code. In HTML you can add comments using the following line: 16
  17. 17. Pengaturcaraan PHP Pengaturcaraan PHPPHP comments are different in thatthey arent sent to the Web browserat all, meaning they wont beviewable to the end user, even whenlooking at the HTML source. PHPsupports three comment types.The first uses the pound or numbersymbol (#). The second uses twobackslashes (//).Both of these cause PHP to ignoreeverything that follows until the end ofthe line (when you press Return orEnter). Thus, these two comments arefor single lines only. They are alsocommonly used to add a comment onthe same line as some PHP code. 17
  18. 18. Pengaturcaraan PHPA third style allows comments to run over multiple lines (/*...*/).Pengaturcaraan PHP 18
  19. 19. Pengaturcaraan PHPPengaturcaraan PHP 19
  20. 20. Pengaturcaraan PHP Using VariablesPengaturcaraan PHP 20
  21. 21. Pengaturcaraan PHPWhat Are Variables?Variables, in short, are containersused to temporarily store values.These values can be numbers, text,or much more complex arrangements.Variables exist at the heart of anyprogramming language, andcomprehending them is key to usingPHP. According to the PHP manual,there are eight types of variables inthe language.Pengaturcaraan PHPRegardless of what type you are creating, all variables in PHP follow certainsyntactical rules:- A variables name — also called its identifier — must start with a dollarsign ($), for example, $name.- The variables name can contain a combination of strings, numbers,and the underscore, for example, $my_report1.- The first character after the dollar sign must be either a letter or anunderscore (it cannot be a number).- Variable names in PHP are case-sensitive. This is a very important fact.It means that $name and $Name are entirely different variables.- Variables can be assigned values using the equals sign (=), also calledthe assignment operator. 21
  22. 22. Pengaturcaraan PHPPengaturcaraan PHP 22
  23. 23. Pengaturcaraan PHPPengaturcaraan PHP 23
  24. 24. Using Strings Pengaturcaraan PHPPengaturcaraan PHPThe first — arguably most important — variable type is strings. Astring is merely a quoted chunk of letters, numbers, spaces,punctuation, and so forth. These are all strings: - February 3, 2005‘ - 1,000‘ - "In watermelon sugar“ - Tobias 24
  25. 25. Pengaturcaraan PHPTo make a string variable, assign a string value to a valid variable name.Pengaturcaraan PHP To print out the value of a string, use either echo() or print(). 25
  26. 26. Pengaturcaraan PHPTo print the value of string within a context, use double quotation marks.Pengaturcaraan PHP 26
  27. 27. Pengaturcaraan PHPPengaturcaraan PHP 27
  28. 28. Pengaturcaraan PHPConcatenating StringsConcatenation — an important tool when creating dynamic Web sites —is like addition for strings and is performed using the concatenationoperator: the period (.).The $address variable now has the value SeattleWashington, which almostachieves the desired result (Seattle, Washington).Pengaturcaraan PHP To improve upon this, I could write the following code so that a space is added to the mix. The result would then be Seattle, Washington. 28
  29. 29. Pengaturcaraan PHPConcatenation also works with strings or numbers. Either of thesestatements will produce the same result Seattle, Washington 98101.Pengaturcaraan PHP Concatenation is commonly used with string variables and can be used extensively when building databases. Now, lets modify the strings.php script to use this new tool. 29
  30. 30. Pengaturcaraan PHPPengaturcaraan PHP 30
  31. 31. Pengaturcaraan PHP Pengaturcaraan PHPAssigning new valuesIf you assign another value to an existing variable (say $book), the new valuewill overwrite the old one. For example:$book = High Fidelity;$book = The Corrections;/* $book now has a value of The Corrections. */Converting the string caseYou can have PHP convert the case of your strings with: strtolower(), whichmakes it entirely lowercase; strtoupper(), which makes it entirely uppercase;ucfirst(), which capitalizes the first character; and ucwords(), whichcapitalizes the first character of every word. 31
  32. 32. Pengaturcaraan PHPOthers Concatenating formatsThe initial example in the concatenating section could be rewritten usingeither$address = "$city, $state";or$address = $city;$address . = , ;$address . = $state;Using the concatenation operator with functionsThe concatenation operator can be used when calling functions, like so:$num = strlen ($first_name . $last_name); Using Numbers Pengaturcaraan PHP 32
  33. 33. Pengaturcaraan PHP PHP has both integer and floating-point (decimal) number types - 8 - 3.14 - 10980843985 - - 4.2398508 - 4.4e2Pengaturcaraan PHPAlong with the standard arithmetic operators you can use on numbers,there are dozens of functions. Two Ill introduce in this lesson are round()and number_format().Arithmetic Operators Operator Meaning + Addition - Subtraction * Multiplication / Division % Modulus ++ Increment -- Decrement 33
  34. 34. Pengaturcaraan PHP The round() function rounds a decimal either to the nearest integer... ..or to a specified number of decimal places.Pengaturcaraan PHPThe number_format() function turns a number into the morecommonly written version, grouped into thousands using commas.For example: 34
  35. 35. Pengaturcaraan PHPThe number_format() function can also set a specified number ofdecimal points.Pengaturcaraan PHP 35
  36. 36. Pengaturcaraan PHPPengaturcaraan PHP 36
  37. 37. Pengaturcaraan PHPCorresponding assignment operatorsMany of the mathematical operators also have a correspondingassignment operator, letting you create a shorthand for assigningvalues. This line$total = $total + ($total * $taxrate);could be rewritten as$total += ($total * $taxrate);Pengaturcaraan PHPUsing functions inline with the echo() statementIf you use concatenation, the number_format(), or any other function,can be used inline with an echo() statement:echo You are purchasing <b> . $quantity . </b> widget(s) at acost of <b>$ . number_format ($price) . </b> each. With tax, the totalcomes to<b>$ . number_format ($total) . </b>.; 37
  38. 38. Pengaturcaraan PHPPengaturcaraan PHP 38
  39. 39. Pengaturcaraan PHPConstants are a specific data typein PHP that, unlike variables, retaintheir initial value throughout thecourse of a script.In fact, you cannot change thevalue of a constant once it hasbeen set.Constants can be assigned anysingle value — a number or astring of characters.Pengaturcaraan PHPTo create a constant, you use the define() function instead of theassignment operator (=) used for variables.Notice that, as a rule of thumb, constants are named using all capitals,although this is not required. Most importantly, constants do not use theinitial dollar sign as variables do (because, technically, constants are notvariables). 39
  40. 40. Pengaturcaraan PHPPrinting constants requires special syntax as well.You cannot print constants using echo "Hello, USERNAME", as PHPwould just print Hello, USERNAME and not the value of theUSERNAME constant (because theres no dollar sign telling PHP thatUSERNAME is anything other than literal text).Pengaturcaraan PHP 40
  41. 41. Pengaturcaraan PHPPengaturcaraan PHP 41
  42. 42. Using Single and Double Quotation Marks Pengaturcaraan PHPPengaturcaraan PHPIn PHP, values enclosed within single quotation marks will be treated literally,whereas those within double quotation marks will be interpreted. In otherwords, placing variables and special characters within double quotes willresult in their represented values printed, not their literal values.These characters have special meanings when used within double quotationmarks. Code MeaningEscaped Characters " Double quotation mark Single quotation mark Backslash n Newline r Carriage return t Tab $ Dollar sign 42
  43. 43. Pengaturcaraan PHPFor example, assume that you have $var = test;The code echo "var is equal to $var"; will print out var is equal to test,whereas the code echo var is equal to $var; will print out var is equalto $var.Using an escaped dollar sign, the code echo "$var is equal to $var";will print out $var is equal to test, whereas the code echo $var isequal to $var; will print out $var is equal to $var. This code... ...prints out... echo "var is equal to $var"; var is equal to test echo var is equal to $var; var is equal to $var echo "$var is equal to $var"; $var is equal to test echo $var is equal to $var; $var is equal to $varPengaturcaraan PHP 43
  44. 44. Pengaturcaraan PHPPengaturcaraan PHP 44
  45. 45. Pengaturcaraan PHP Pengaturcaraan PHPSingle quotes can be easier than double quotesAs valid HTML often includes a lot of double-quoted attributes, its ofteneasiest to use single quotation marks when printing HTML with PHP.echo <table width="80%" border="0"cellspacing="2" cellpadding="3"align="center">;If you were to print out this HTML using double quotation marks, you wouldhave to escape all of the double quotation marks in the string.echo "<table width="80%"border="0" cellspacing="2"cellpadding="3" align= "center">"; 45
  46. 46. EndPengaturcaraan PHP 46