the php hypertext pre

Upload: qwerty

Post on 28-Feb-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/25/2019 The PHP Hypertext Pre

    1/36

    PHP HYPERTEXT PRE-PROCESSOR (PHP)

    The PHP Hypertext Pre-processor (PHP) is a programming language that allows webdevelopers to create dynamic content that interacts with databases. PHP is basically usedfor developing web based software applications.

    PHP is a recursive acronym for "PHP: Hypertext Preprocessor".PHP is a server side scripting language that is embedded in HTML. It is used to managedynamic content, databases, session tracking, even build entire e-commerce sites.

    It is integrated with a number of popular databases, including MySQL, PostgreSQL,Oracle, Sybase, Informix, and Microsoft SQL Server

    Common uses of PHP:

    PHP performs system functions, i.e. from files on a system it can create, open,

    read, write, and close them. PHP can handle forms, i.e. gather data from files, save data to a file, thru email

    you can send data, return data to the user. You add, delete, modify elements within your database thru PHP. Access cookies variables and set cookies. Using PHP, you can restrict users to access some pages of your website. It can encrypt data.

    PHP is a powerful server-side scripting language for creating dynamic and interactivewebsites.

    PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft'sASP. PHP is perfectly suited for Web development and can be embedded directly into theHTML code.

    PHP file

    A PHP file may contain text, HTML tags and scripts. Scripts in a PHP file areexecuted on the server.

    PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php"

    What You Should Already KnowBefore you continue you should have a basic understanding of the following: HTML / XHTML Some scripting knowledge

    Where to Start?

    Install an Apache server on a Windows or Linux machine

  • 7/25/2019 The PHP Hypertext Pre

    2/36

    Install PHP on a Windows or Linux machine Install MySQL on a Windows or Linux machine

    Basic PHP Syntax

    A PHP scripting block always starts with . A PHP scripting

    block can be placed anywhere in the document.

    In other words the PHP code is enclosed within special start and end tags which denotethe start and end of the PHP script, these tags are. When a PHP file is requested by a Webbrowser a PHP interpreter parses through the file ignoring everything and anything until aspecial start tag is encountered. The PHP interpreter will then from that point on interpretthe code found replacing the PHP script with the output it generates at that point in thedocument until a special close tag is encountered. At which time the interpreter continuesparsing the document

    PHP - Echo

    As you saw in the previous lesson, the PHP function echo is a means of outputting text tothe web browser. Throughout your PHP career you will be using the echo function morethan any other

    Example One

    First Example

  • 7/25/2019 The PHP Hypertext Pre

    3/36

    echo Hello World;?>

    Example Two

    My First PHP Page

    Example Three

    Within a document you can embed PHP start and end tags and code at manypoints, consider the following example:

    This is not.

  • 7/25/2019 The PHP Hypertext Pre

    4/36

    echo '

    This is also PHP script generated.

    ';?>

    The Semicolon!

    PHP requires instructions to be terminated with a semicolon at the end ofeach statement.

    Example Four

    My First PHP Page

    Commenting PHP Code:

    A comment is the portion of a program that exists only for the human readerand stripped out before displaying the programs result. There are twocommenting formats in PHP:

    PHP supports a number of different styles of comments// this is a single line comment/* this comment is an example ofa multi-line comment */

  • 7/25/2019 The PHP Hypertext Pre

    5/36

    separate lines of the web browser */echo '

    Hello, World!

    '; // This is the first Hello, World!echo '

    Hello, World!

    '; // This is the second.?>

    PHP - Variables

    Variables can be thought of as containers which hold data. The data held bya variable can change during the execution of a PHP script, hence the name

    variable.

    A variable is a means of storing a value, such as text string "Hello World!"or the integer value 4.

    Variables in PHP are represented by a $ symbolfollowed by the name of

    the variable.

    $var_name = value;

    $name = Simon;

    NB:PHP variable names are case sensitive. Therefore the variable $name is a differentvariable to $Name. Be careful!

    PHP Variable Naming ConventionsThere are a set of rules which need to be considered in naming your variables.A valid variable name can start with a letter or an underscorecharacter, followed by anynumber of letters, numbers or underscores

    The following script illustrates some example valid variables:

  • 7/25/2019 The PHP Hypertext Pre

    6/36

    The following variables are all invalid:

    var = Simon; // Invalid - does not start with a $ symbol

    $2var = Simon; // Invalid name starts with a number

    PHP is a Loosely Typed Language

    PHP automatically converts the variable to the correct data type, dependingon how they are set.

    In a strongly typed programming language, you have to declare (define) thetype and name of the variable before using it.

    PHP Variable TypesVariable data is stored in the computers memory but the computer needs to know in whatformat the data should be stored as different types of data take up different amounts ofspace. The format of a piece of data is known as its data type and PHP supports eightprimitive types. PHP has a total of eight data types which we use to construct ourvariables:

    Integers: are whole numbers, without a decimal point, like 4195. Doubles: are floating-point numbers, like 3.14159 or 49.1.

    Booleans: have only two possible values either true or false. NULL: is a special type that only has one value: NULL. Strings: are sequences of characters, like 'PHP supports string operations.' Arrays: are named and indexed collections of other values.

    Objects: are instances of programmer-defined classes, which can package upboth other kinds of values and functions that are specific to the class.

    Resources: are special variables that hold references to resources external to PHP(such as database connections).

  • 7/25/2019 The PHP Hypertext Pre

    7/36

    Therefore, the following illustrates variable names:

    $strName = 'Elizabeth'; $intAge = 34; $booAnswer = True; $intNumber = 5; $intAnotherNumber = -5; $floNumber = 1.234;

    Strings

    A string is a series of characters. We have used strings in our previous PHP examples butit is now time to explain that PHP has three different ways in which strings can bespecified.

    Backslash (\) character

    If we were to simply enclose this in single quotes the PHP interpreter would not knowwhich single quote indicated the end of the string:

    'Hello Im Simon'

    To overcome this problem PHP uses a backslash (\) character known as escape to allowus to include single quotations within our strings. Therefore the above string would looklike this:

    'Hello I\m Simon'

    NB.Strings in PHP can be very large. You dont need to worry about using long strings!

  • 7/25/2019 The PHP Hypertext Pre

    8/36

    String OperatorsPHP supports two string operators.

    My First PHP Page

  • 7/25/2019 The PHP Hypertext Pre

    9/36

    $strFullname = $strFirstname . $strSurname;echo "

    $strFirstname joined with $strSurname is $strFullname

    ";$strFullname = $strFirstname . " " . $strSurname;echo "

    $strFirstname joined with $strSurname with a space is$strFullname

    ";$strFullname = $strFirstname;$strFullname .= " ";$strFullname .= $strSurname;echo "

    $strFirstname joined with $strSurname with a space is$strFullname

    ";?>

    PHP Decision Making (Sequential Execution)

    if...else statement- use this statement if you want to execute a set of code when acondition is true and another if the condition is not true elseif statement- is used with the if...else statement to execute a set of code

    if one of several condition are true switch statement- is used if you want to select one of many blocks of code to be

    executed, use the Switch statement. The switch statement is used to avoid long blocks of

    if..elseif..else code.

    The If...Else StatementIf you want to execute some code if a condition is true and another code if a condit ion isfalse, use the if....else statement.

    Syntax

  • 7/25/2019 The PHP Hypertext Pre

    10/36

    if (condition)code to be executed if condition is true;

    elsecode to be executed if condition is false;

    Brace characters may be used to ({ }) to group all statements that you wish toconditionally execute into a statement group, for example:

    Braces can be formatted so that they appear like the example above:If ( expression ) {

    }Alternatively they can appear on separate lines:If ( expression ){

    }

  • 7/25/2019 The PHP Hypertext Pre

    11/36

    The if else constructSometimes you may wish to execute a certain statement if a condition is met and anotherstatement if it is not. This is accomplished using the else statement which extends the ifconstruct.

    The structure of the if - else construct is as follows:

    if ( expression )

    statement to be executed if condition is trueelse

    statement to be executed if condition is false

  • 7/25/2019 The PHP Hypertext Pre

    12/36

    elseif ( expression )statement to be executed if elseif condition is true

    else

    switch constructThe switch construct is similar to a series of if statements acting on the same conditionalexpression. The switch construct is used when you wish to compare a variable against anumber of different values and execute different code statements depending on thevariables value.

    The case construct consists of a switch component in which an expression is evaluated.

    The result of the expression is then compared in turn to a list of case statements. The firstcase value which matches to the expression will determine which associated statementsare executed

    The syntax of the switch statement is:switch ( expression ){case constant expression : statement

    case constant expression : statement...

    default : statement

    }

  • 7/25/2019 The PHP Hypertext Pre

    13/36

    echo "

    Hello Elizabeth

    ";case "Hayley":echo "

    Hello Hayley

    ";case "Alan":echo "

    Hello Alan

    ";

    }?>

    Switch and break

    The break statement can be used to end the current execution of a switch statement.

  • 7/25/2019 The PHP Hypertext Pre

    14/36

    PHP Loops

    While loops

    while ( expression ){statement

    }

    Do while loops

    do{statementstatement

  • 7/25/2019 The PHP Hypertext Pre

    15/36

    }while ( expression );

    For loopThere are three expressions incorporated into the for construct.The syntax for the loop is:for (expression; expression; expression){

    statementstatement

    }

  • 7/25/2019 The PHP Hypertext Pre

    16/36

    foreach loopPHP supports a special loop construct for accessing the contents of arraysUsed in Array Examples

    ArraysAn array in PHP is actually an ordered map, where a map is a type which maps values tokeys. Because PHP stores its arrays as maps it means that they can be used for a wholevariety of different data structures such as lists, trees, stacks etc. Arrays are used tocollect together data, such as peoples names and perform operations on this data aseasily as possible. PHP supports both single and multi-dimensional arrays, but for nowlets look at creating a very simple array.

    Arrays are created using the array construct:

    theArray = array (arrayItem1, arrayItem2, );

    Example

    $arrColours = array (Red, Green, Blue, Yellow, White);

    This creates an array called $arrColours which contains 5 elements storing variouscolours. We can refer to the elements within the array by using a subscript to the arrayname. Because the index defaults to numbering the array index from 0 to in this case to 4then we can access the first element of the array by the following statement:

    $arrColours[0];

    and the last element of the array by:

    $arrColours[4];

    Example

  • 7/25/2019 The PHP Hypertext Pre

    17/36

    Array Output

    An Array with a KeyWe can create an array and specify our own index key at the same time.

    $arrColours = array (0=>Red, 1=>Green, 2=>Blue, 3=>Yellow,

    4=>White);

    A key index can be specified using the operator =>. In the above example the index hasbeen specified exactly as the default index would, a numerical index starting from 0 andincremented by one each time. But what if we put the index items in a different order and

    even missed out an index number, for example:

    $arrColours = array (0=>Red, 2=>Green, 3=>Blue, 5=>, 1=>Yellow,

    4=>White);

    In the above example the index has not been created in numerical order and in addition ablank index key, number 5 has been included. If we use the above array with a slightlymodified version of our simple for loop example before we can see what is displayedwhen we cycle through the array:

  • 7/25/2019 The PHP Hypertext Pre

    18/36

    The output from the script is shown in Figure below

    Foreach

    PHP includes a loop construct specifically designed for iterating through arrays. Thisloop construct is known as the foreach loop and there are two syntaxes. The first form is:

    foreach (array as value) statement

    The foreach loop will iterate through the array provided by array. The value in the current

    index is assigned to value. The array index is then incremented by one so the nextiteration of the loop will access the next element of the array. An example of this loop hasbeen included in the following script that is a rewrite of the previous one:

  • 7/25/2019 The PHP Hypertext Pre

    19/36

    Note that the output of the colours is also in the order in which they were declared,

    not in the numerical index order, as with the for loop.

    This foreach statement is similar to the previous example but in addition assigns the valueof the current elements index to the key. This is shown in the following script:

  • 7/25/2019 The PHP Hypertext Pre

    20/36

    Arrays and non numerical keysArrays dont have to have a numerical key, for example:

    $arrColours = array (red=>Red, green=>Green, blue=>Blue,

    yellow=>Yellow, white=>White);

    The following script illustrates the use of such an array:

  • 7/25/2019 The PHP Hypertext Pre

    21/36

    PHP FunctionsThe real power of PHP comes from its functions.In PHP - there are more than 700 built-in functions available.

    Create a PHP Function

    A function is a block of code that can be executed whenever we need it.

    Creating PHP functions:

    function functioname()

    {

    Code to be executed

    }

  • 7/25/2019 The PHP Hypertext Pre

    22/36

    PHP Fun ct ions - Adding parameters

    To add more functionality to a function, we can add parameters. The parameters arespecified inside the parentheses.

    The output of the code above will be:

    My name is Kai Jim Refsnes.My name is Hege Refsnes.My name is Stale Refsnes.

  • 7/25/2019 The PHP Hypertext Pre

    23/36

    The output of the code above will be:

    My name is Kai Jim Refsnes.My name is Hege Refsnes!My name is Stle Refsnes...

    PHP Fun ct ions - Return values

    Functions can also be used to return values.Example

    PHP and Form InteractionPHP can use forms to allow a script to interact with the user.Using forms to interact with PHP we start by creating an XHTML web form

    PHP Forms and User Input

    The PHP $_GET and $_POST variables are used to retrieve information from

    forms, like

    user input.

    PHP $_GET

    The $_GET variable is used to collect values from a form with method="get".

    The $_GET Vari able

    The $_GET variable is an array of variable names and values sent by the HTTP GET

    method.The $_GET variable is used to collect values from a form with method="get".Information sent from a form with the GET method is visible to everyone (it will bedisplayed in the browser's address bar) and it has limits on the amount of information tosend (max. 100 characters).

    Example

  • 7/25/2019 The PHP Hypertext Pre

    24/36

    Name:

    Age:

    When the user clicks the "Submit" button, the URL sent could look something like this:

    http://www.w3schools.com/welcome.php?name=Peter&age=37

    The "welcome.php"file can now use the $_GET variable to catch the form data (noticethat the names of the form fields will automatically be the ID keys in the $_GET array):

    Welcome .
    You are years old!

    Note: When using the $_GET variable all variable names and values are displayed in theURL. So this method should not be used when sending passwords or other sensitiveinformation.

    Note: The HTTP GET method is not suitable on large variable values; the value cannotexceed 100 characters.

    PHP $_POSTThe $_POST variable is used to collect values from a form with method="post".The $_POST variable is an array of variable names and values sent by the HTTP POSTmethod.

    The $_POST variable is used to collect values from a form with method="post".Information sent from a form with the POST method is invisible to others and has nolimits on the amount of information to send.

    Note:Variables sent with HTTP POST are not shown in the URLNote:Variables have no length limit

    The $_REQUEST Vari able

    The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and$_COOKIE.

    The PHP $_REQUEST variable can be used to get the result from form data sent withboth the GET and POST methods.

    ExampleWelcome .
    You are years old!

  • 7/25/2019 The PHP Hypertext Pre

    25/36

    PHP Form HandlingThe most important thing to notice when dealing with HTML forms and PHP is that anyform element in an HTML page will automaticallybe available to your PHP scripts. i.e

    create the PHP script which the XHTML form invokes.

    The example1 HTML page below contains two input fields and a submit button. Whenthe user fillsin this form and click on the submit button, the form data is sent to the "welcome.php"file.

    Name:

    Age:

    welcome.php" fileWelcome .

    You are years old.

    Accessing form data is essentially very easy. When a form is created an associated arrayof variables is created. This array is called $_POST. Each HTML form element that has aunique name is stored in the array and can be accessed by the PHP script. The $_POST

    syntax is as follows:

    $_POST["name"];

    name is the name of the form value we wish to access. In our example we have assignedthe contents of each of our form fields into variables of the same name:

    $strFirstname = $_POST["strFirstname"];

  • 7/25/2019 The PHP Hypertext Pre

    26/36

    $strSurname = $_POST["strSurname"];$strUsername = $_POST["strUsername"];$strPassword = $_POST["strPassword"];

    The values of these variables are then finally displayed using a couple of echo

    statements.

    The example2HTML page below contains several input fields and a submit button. When the userfills in this form and click on the submit button, the form data is sent to the "example1.php" file.

    Please enter your personal details:Firstname
    Surname
    Username

    Password

    Combining PHP and FormsWhat we are going to do is to combine our XHTML form and PHP script together in asingle document. When the form submit button is clicked the form will invoke itself andprocess the PHP script within it.

  • 7/25/2019 The PHP Hypertext Pre

    27/36

    Please enter your personal details:

    Firstname:

    Surname:

    Username:

    Password:

    When the page is viewed for the first time the output from the PHP statements isvisible and as no form data has been sent yet the variables contain no values, hencethe strange looking output displayed after the form.

    This is not a see that when problem after the form is submitted but the first time thepage is loaded the form variables contain no data and this results in the display of anincomplete message. What we need is a means of determining if the form data wassubmitted or not, and here it is:

    Please enter your personal details:

    Firstname:

  • 7/25/2019 The PHP Hypertext Pre

    28/36

    Surname:

    Username:

    Password:

    PHP MySQL Introduction

    A database is a structured collection of data. Databases occurred in the real world beforecomputers were invented. Examples of real world databases include: TV times guide Filing cabinet of documents

    Telephone book

    What is MySQL?MySQL is a database. A database defines a structure for storing information.

    Relational DatabaseIn relational database systems such as MySQL data is organized into tables

  • 7/25/2019 The PHP Hypertext Pre

    29/36

    Database Tables

    A database most often contains one or more tables. Each table has a name (e.g."Customers" or "Orders"). Each table contains records (rows) with dat

    We see that it contains a table called Customers. This table consists of three column fields ofdata entitled Title, Surname and Firstname. The data is inserted into each of these fieldsforming a number of record rows within the table. Queries

    Database queries

    A query is a question or a request.With MySQL, we can query a database for specific information and have a recordsetreturned.

    Connecting to a MySQL DBMS

    PHP MySQL Connect to a Database

    The free MySQL Database is very often used with PHP

    Connecting to a MySQL DBMSIn order for a PHP script to access a database we need to form a connection from the script tothe database management system (DBMS). To do this we use the mysql_connect() function

  • 7/25/2019 The PHP Hypertext Pre

    30/36

    resourceId mysql_connect(server, username, password);or

    mysql_connect(servername,username,password);

    The mysql_connect() function requires three parameters. The first is the name of the server,

    the second is your username and the third your password.

    If you are developing on your own standalone computer the format of this function maylook like this with the value of server set to be localhost, the username as root andwhatever password you have set:

    $dbLocalhost = mysql_connect("localhost", "root", "password")

    Select the database

    Having created a link to the DBMS we wish to access the next stage is to select the databasethat we wish to use. This is done using the function mysql_select_db()which allows us tospecify which database at the location defined in the mysql_connect() function we wish toaccess.

    bool mysql_select_db(databasename, resourceId)

    The mysql_select_db() function requires two parameters. The first is the name of thedatabase you wish to access and the second is the resourceId which was returned frominvoking the previous mysql_connect() function. The function returns true if the databaseselection worked or false if not.

    mysql_select_db(glassesrus, $dbLocalhost)

    The die() function

    The die() function is combined with an or operator in order to stop execution of the scriptif the previous database connection could not be formed, it looks like this:

  • 7/25/2019 The PHP Hypertext Pre

    31/36

    die (Error Message)

    Function die()has a single parameter which is a message which is displayed beforeexecution is stopped.

    It is common practice to combine the use of function die()with that of function.mysql_error()which returns the text of the error message from the previous MySQLoperation

    Combining function die() and function mysql_error() looks like this:The mysql_error()function requires no parameters and returns an error message string.

    die("Could not connect: " . mysql_error())

    Combining the die() function along with the mysql_connect() function requires us to usethe or construct like this:

    $dbLocalhost = mysql_connect("localhost", "root", "password")or die("Could not connect: " . mysql_error());

    The above code fragment should now be read as form a mysql connection to localhost

    and if this doesnt work stop thescript

    We are now ready to form these functions together into our first PHP script and here it is:

    The above script opens a connection to the DBMS server and then attempts to selectdatabase glassesrus.

    Reading a Database

    The next step in linking PHP to a database is to get it to send a Structured QueryLanguage (SQL) statement to the database in order to begin to retrieve data records.

    To do this we need to introduce a new function that of mysql_query()

    resourceRecords mysql_query (query, resourceId);

  • 7/25/2019 The PHP Hypertext Pre

    32/36

    Function mysql_query() requires two parameters, the first is an SQL query string and thesecond is the database resource identifier returned from the mysql_connect() function.

    Example

    $dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)

    Adding this function into our script gives us.

    Now the mysql_query() function returns us a resource pointer to all the records whichmatch the SQL statement we supplied. This could be zero, one or many records. What weneed is a function which will return the contents of one record cell from the record set.This function is called mysql_result():

    fielddata mysql_result (resourceRecords, row, field);

    The mysql_query() function requires three parameters. The first is the resource pointer tothe records returned by the mysql_query() function. The second is the number

    indicating which record to return, with 0 being the first record, 1 the second and so on.The third parameter is the name of the database field to return. The function returns thedata stored in the field. Here is an example of the function:

    $strSurname = mysql_result($dbRecords, 0, surname);

    Adding this function into our script gives us.

  • 7/25/2019 The PHP Hypertext Pre

    33/36

    Viewing a Whole Record

    Viewing All Returned Records

    To display all the records which are returned from mysql_query() we need to introduce anew function called mysql_fetch_row():

    array mysql_fetch_row(resourceRecords);

    The function requires a single parameter which is the resource identifier returned fromthe mysql_result() function. It returns an array containing the database record. Whenthis new function is combined with a loop construct we can access and display all of the

    records returned.

  • 7/25/2019 The PHP Hypertext Pre

    34/36

    This function returns a single database record and stores this in the array $arrRecord.When the last record has been returned mysql_fetch_row()returns false and the loopwill stop iterating.Within the loop a number of echo statements are used to display the fields. The fields arestored within the $arrRecord array and are accessed through each array element, 0, 1, 2

    and 3.

    mysql_fetch_array()

    The function mysql_fetch_array() is an extended version of function mysql_fetch_row():

    Like the mysql_fetch_row() function the mysql_fetch_array() function requires a singleparameter which is the resource identifier returned from the mysql_result() function. Itreturns an array containing the database record.

    The one thing that does differ from the mysql_fetch_row() function is that we can refer tothe database fields by name.

    Inserting New Records

    We can create new database records. To do this we need a new SQL statement, theINSERT INTO query which looks like this:

    INSERT INTO table (field1, field2, ) VALUES ('value1', 'value2', )

  • 7/25/2019 The PHP Hypertext Pre

    35/36

  • 7/25/2019 The PHP Hypertext Pre

    36/36

    UPDATE table SET field1='value1', field2='value2' WHERE field='value'

    The UPDATE statement requires you to specify the name of the table in which to update,provide a list of the fields and their new updated values and finally indicate whichrecords should be updated with these values.