MOdule Recovered

Embed Size (px)

Citation preview

  • 8/7/2019 MOdule Recovered

    1/78

  • 8/7/2019 MOdule Recovered

    2/78

    In 1995 Rasmus Lerdorfmade a set of scripts based on PERLto access his resume and named it as PHP / FI stands for PersonalHome Page / Forms Interpreter. In 1997 Rasmus released PHP / FI 2.0with a large C-implementation and it received rapid fame due to itsease of use and C like syntax as it was easy for C programmers toadopt and its programming rules were comparatively simple than C

    language. After some beta versions of PHP / FI 2.0 finally Alpha PHP3.0 was released later.

    In 1997 Andi Gutmans and Zeev Suraski worked togetherwith Rasmus to completely rewrite the language and introduce a morepowerful language known as PHP 3.0. Shortly after PHP 3.0 in 1998PHP 4 came on the screen with improved performance for complexapplications and in 2004 finally PHP 5.0 was released with a newobject model and plenty of new features.

    Why PHP?

    If you are still confused that why you should use PHP then answer isvery straight forward - if you want to make a web application that cantake input from users and can process it to generate certain outputthen you will need PHP to work for you on server side and response todifferent events generated from client side accordingly. For example ifyou want to make an Online Shopping Store for your Video Gamesbusiness where people can browse different categories of games andcan shop of their choice and finally can pay you online in real time.

    2

  • 8/7/2019 MOdule Recovered

    3/78

    MODULE 2

    (Basic PHP Syntax)

    A PHP file normally contains HTML tags, just like an HTML file, and

    some PHP scripting code.

    Below, we have an example of a simple PHP script which sends thetext "Hello World" to the browser:

    A PHP scripting block always starts with . A

    PHP scripting block can be placed anywhere in the document.

    Each code line in PHP must end with a semicolon. The semicolon is aseparator and is used to distinguish one set of instructions fromanother.

    There are two basic statements to output text with PHP: echo andprint. In the example above we have used the echo statement tooutput the text "Hello World".

    Comments in PHP

    In PHP, we use // to make a single-line comment or /* and */ to makea large comment block.

    3

  • 8/7/2019 MOdule Recovered

    4/78

    MODULE 3

    (Variables in PHP)

    All variables in PHP start with a $ sign symbol. Variables may contain

    strings, numbers, or arrays.

    There are four major types of variables: integers, floating pointnumbers, strings and arrays. Assigning values to variables is easy.The single and double quotes work the same as the echo statementabove.

    Below, the PHP script assigns the string "Hello World" to a variablecalled $txt:

    To concatenate two or more variables together, use the dot (.)operator:

    The output of the script above will be: "Hello World 1234".

    4

  • 8/7/2019 MOdule Recovered

    5/78

    MODULE 4

    (PHP Form Handling)

    The most important thing to notice when dealing with HTML forms and

    PHP is that any form element in an HTML page will automatically beavailable to your PHP scripts.

    The $_GET Variable

    The $_GET variable is an array of variable names and values sent bythe HTTP GET method.

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

    characters).

    Example:

    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 theform data (notice that the names of the form fields will automaticallybe the ID keys in the $_GET array):

    Welcome .
    You are years old!

    Why use $_GET?Note: When using the $_GET variable all variable names and valuesare displayed in the URL. So this method should not be used whensending passwords or other sensitive information! However, becausethe variables are displayed in the URL, it is possible to bookmark thepage. This can be useful in some cases.

    Note: The HTTP GET method is not suitable on large variable values;

    5

  • 8/7/2019 MOdule Recovered

    6/78

  • 8/7/2019 MOdule Recovered

    7/78

    Look at the following example of an HTML form:

    Enter your name: Enter your age:

    The example HTML page above contains two input fields and a submitbutton. When the user fills in this form and hits the submit button, the"welcome.php" file is called.

    The "welcome.php" file looks like this:

    Welcome .
    You are years old!

    A sample output of the above script may be:

    Welcome John.You are 28 years old!

    Here is how it works: The $_POST["name"] and $_POST["age"]variables are automatically set for you by PHP. The $_POST containsall POST data.

    Note: If the method attribute of the form is GET, then the forminformation will be set in $_GET instead of $_POST.

    HTML has two methods for passing form variables, POST and GET. GETdisplays the input in the URL while POST hides it. Variables passed via

    POST are represented by $_POST["{name of input tag}"] GET uses$_GET[] respectively. Also $_REQUEST[] will take the values of eitherPOST or GET. $_REQUEST also will return variables passed in a URLnot from a form.

    7

  • 8/7/2019 MOdule Recovered

    8/78

    MODULE 5

    (Conditional Statements)

    Conditional statements in PHP are used to perform differentactions based on different conditions.

    Conditional Statements

    Very often when you write code, you want to perform different actionsfor different decisions. You can use conditional statements in yourcode to do this.

    In PHP we have two conditional statements:

    if (...else) statement - use this statement if you want toexecute a set of code when a condition is true (and another ifthe condition is not true)

    switch statement - use this statement if you want to selectone of many sets of lines to execute

    The If Statement

    If you want to execute some code if a condition is true and another

    code if a condition is false, use the if....else statement.

    Syntax

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

    elsecode to be executed if condition is false;

    Example

    The following example will output "Have a nice weekend!" if the

    current day is Friday, otherwise it will output "Have a nice day!":

  • 8/7/2019 MOdule Recovered

    9/78

    echo "Have a nice day!";?>

    If more than one line should be executed when a condition is true, the

    lines should be enclosed within curly braces:

    The Switch Statement

    If you want to select one of many blocks of code to be executed, usethe Switch statement.

    Syntax

    switch (expression){case label1: code to be executed if expression = label1;break;

    case label2: code to be executed if expression = label2;break;

    default: code to be executedif expression is different

    from both label1 and label2;

    }

    Example

    This is how it works: First we have a single expression (most often avariable), that is evaluated once. The value of the expression is thencompared with the values for each case in the structure. If there is amatch, the block of code associated with that case is executed. Usebreak to prevent the code from running into the next caseautomatically. The default statement is used if none of the cases aretrue.

    9

  • 8/7/2019 MOdule Recovered

    10/78

    10

  • 8/7/2019 MOdule Recovered

    11/78

    MODULE 6(Looping)

    Looping statements in PHP are used to execute the same blockof code a specified number of times.

    Looping

    Very often when you write code, you want the same block of code torun a number of times. You can use looping statements in your code toperform this.

    In PHP we have the following looping statements:

    while - loops through a block of code if and as long as aspecified condition is true

    do...while - loops through a block of code once, and thenrepeats the loop as long as a special condition is true

    for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an

    array

    The while Statement

    The while statement will execute a block of code if and as long as acondition is true.

    Syntax

    while (condition)code to be executed;

    Example

    The following example demonstrates a loop that will continue to run aslong as the variable i is less than, or equal to 5. i will increase by 1each time the loop runs:

  • 8/7/2019 MOdule Recovered

    12/78

    }?>

    The do...while Statement

    The do...while statement will execute a block of code at least once -it then will repeat the loop as long as a condition is true.

    Syntax

    Do{code to be executed;

    }while (condition);

    Example

    The following example will increment the value of i at least once, and itwill continue incrementing the variable i while it has a value of lessthan 5:

    The for Statement

    The for statement is used when you know how many times you want

    to execute a statement or a list of statements.

    12

  • 8/7/2019 MOdule Recovered

    13/78

    Syntax

    for (initialization; condition; increment){ code to be executed;}

    Note: The for statement has three parameters. The first parameter isfor initializing variables, the second parameter holds the condition, andthe third parameter contains any increments required to implementthe loop. If more than one variable is included in either theinitialization or the increment section, then they should be separatedby commas. The condition must evaluate to true or false.

    Example

    The following example prints the text "Hello World!" five times:

    The foreach Statement

    Loops over the array given by the parameter. On each loop, the valueof the current element is assigned to $value and the array pointer isadvanced by one - so on the next loop, you'll be looking at the nextelement.

    Syntax

    foreach (array as value){ code to be executed;}

    Example

    The following example demonstrates a loop that will print the values ofthe given array:

    13

  • 8/7/2019 MOdule Recovered

    14/78

  • 8/7/2019 MOdule Recovered

    15/78

  • 8/7/2019 MOdule Recovered

    16/78

    Associative ArraysAssociative arrays store value data in keys

    To create an associative array with array( ), use the => symbolto separate indexes from values:

    $price = array('Gasket' => 15.29,

    'Wheel' => 75.25,'Tire' => 50.00);

    Notice the use of whitespace and alignment. We could havebunched up the code, but it wouldn't have been as easy to read:

    $price =array('Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00);

    To construct an empty array, pass no arguments to array( ):

    $addresses = array( );

    You can specify an initial key with => and then a list of values.The values are inserted into the array starting with that key, withsubsequent values having sequential keys:

    $days = array(1 => 'Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday', 'Sunday');

    // 2 is Tuesday, 3 is Wednesday, etc.

    Outputs name : Jon Smith - phone : 555-555-1234 - address : 1010Home Cir - city : Atlanta - state : GA - zipcode : 30060 - email :[email protected]

    We'll get into the foreach loop a little later but for every value of$assoc it set the key equal to $key and the value to $value and thenused the echo statement to display the values

    16

  • 8/7/2019 MOdule Recovered

    17/78

    Multidimensional arrays

    This stores an array inside an array. To retrieve a value use echo$info["Jon"]["city"] will display Atlanta.

    The values in an array can themselves be arrays. This lets youeasily create multidimensional arrays:

    $row_0 = array(1, 2, 3);$row_1 = array(4, 5, 6);$row_2 = array(7, 8, 9);$multi = array($row_0, $row_1, $row_2);

    You can refer to elements of multidimensional arrays byappending more []s:

    $value = $multi[2][0]; // row 2, column 0.$value = 7

    To interpolate a lookup of a multidimensional array, you must

    enclose the entire array lookup in curly braces:

    echo("The value at row 2, column 0 is {$multi[2][0]}\n");

    Failing to use the curly braces results in output like this:

    The value at row 2, column 0 is Array[0]

    PHP Array Functions

    Function Descriptionarray() Creates an array

    array_change_key_case()

    Returns an array with all keys in lowercase oruppercase

    array_chunk() Splits an array into chunks of arrays

    array_combine() Creates an array by using one array for keys andanother for its values

    17

  • 8/7/2019 MOdule Recovered

    18/78

    array_count_values() Returns an array with the number of occurrences foreach value

    array_diff() Compares array values, and returns the differences

    array_diff_assoc() Compares array keys and values, and returns the

    differencesarray_diff_key() Compares array keys, and returns the differences

    array_diff_uassoc() Compares array keys and values, with an additionaluser-made function check, and returns thedifferences

    array_diff_ukey() Compares array keys, with an additional user-madefunction check, and returns the differences

    array_fill() Fills an array with values

    array_filter() Filters elements of an array using a user-madefunction

    array_flip() Exchanges all keys with their associated values in anarray

    array_intersect() Compares array values, and returns the matches

    array_intersect_assoc()

    Compares array keys and values, and returns thematches

    array_intersect_key() Compares array keys, and returns the matches

    array_intersect_uassoc()

    Compares array keys and values, with an additionaluser-made function check, and returns the matches

    array_intersect_ukey() Compares array keys, with an additional user-madefunction check, and returns the matches

    array_key_exists() Checks if the specified key exists in the array

    array_keys() Returns all the keys of an array

    array_map() Sends each value of an array to a user-madefunction, which returns new values

    array_merge() Merges one or more arrays into one array

    array_merge_recursive()

    Merges one or more arrays into one array

    array_multisort() Sorts multiple or multi-dimensional arrays

    18

  • 8/7/2019 MOdule Recovered

    19/78

    array_pad() Inserts a specified number of items, with a specifiedvalue, to an array

    array_pop() Deletes the last element of an array

    array_product() Calculates the product of the values in an array

    array_push() Inserts one or more elements to the end of an array

    array_rand() Returns one or more random keys from an array

    array_reduce() Returns an array as a string, using a user-definedfunction

    array_reverse() Returns an array in the reverse order

    array_search() Searches an array for a given value and returns thekey

    array_shift() Removes the first element from an array, and returns

    the value of the removed element

    array_slice() Returns selected parts of an array

    array_splice() Removes and replaces specified elements of an array

    array_sum() Returns the sum of the values in an array

    array_udiff() Compares array values in a user-made function andreturns an array

    array_udiff_assoc() Compares array keys, and compares array values in a

    user-made function, and returns an array

    array_udiff_uassoc() Compares array keys and array values in user-madefunctions, and returns an array

    array_uintersect() Compares array values in a user-made function andreturns an array

    array_uintersect_assoc()

    Compares array keys, and compares array values in auser-made function, and returns an array

    array_uintersect_uassoc()

    Compares array keys and array values in user-madefunctions, and returns an array

    array_unique() Removes duplicate values from an array

    array_unshift() Adds one or more elements to the beginning of anarray

    array_values() Returns all the values of an array

    19

  • 8/7/2019 MOdule Recovered

    20/78

    array_walk() Applies a user function to every member of an array

    array_walk_recursive() Applies a user function recursively to every memberof an array

    arsort() Sorts an array in reverse order and maintain index

    associationasort() Sorts an array and maintain index association

    compact() Create array containing variables and their values

    count() Counts elements in an array, or properties in anob ect

    current() Returns the current element in an array

    each() Returns the current key and value pair from an array

    end() Sets the internal pointer of an array to its lastelement

    extract() Imports variables into the current symbol table froman array

    in_array() Checks if a specified value exists in an array

    key() Fetches a key from an array

    krsort() Sorts an array by key in reverse order

    ksort() Sorts an array by key

    list() Assigns variables as if they were an array

    natcasesort() Sorts an array using a case insensitive "natural order"algorithm

    natsort() Sorts an array using a "natural order" algorithm

    next() Advance the internal array pointer of an array

    pos() Alias of current()

    prev() Rewinds the internal array pointer

    range() Creates an array containing a range of elements

    reset() Sets the internal pointer of an array to its firstelement

    rsort() Sorts an array in reverse order

    shuffle() Shuffles an array

    20

  • 8/7/2019 MOdule Recovered

    21/78

  • 8/7/2019 MOdule Recovered

    22/78

    MODULE 8

    (Operators)

    Operators are used to operate on values.

    PHP Operators

    This section lists the different operators used in PHP.

    Arithmetic Operators

    22

  • 8/7/2019 MOdule Recovered

    23/78

    Operator Description Example Result

    + Addition x=2

    x+2

    4

    - Subtraction x=2

    5-x

    3

    * Multiplication x=4x*5 20

    / Division 15/5

    5/2

    3

    2.5

    % Modulus (division remainder) 5%2

    10%810%2

    1

    20

    ++ Increment x=5x++

    x=6

    -- Decrement x=5x--

    x=4

    Assignment Operators

    Operator Example Is The Same As

    = x=y x=y

    += x+=y x=x+y

    -= x-=y x=x-y

    *= x*=y x=x*y

    /= x/=y x=x/y

    %= x%=y x=x%y

    Comparison Operators

    Operator Description Example

    == is equal to 5==8 returns false

    != is not equal 5!=8 returns true

    > is greater than 5>8 returns false

    < is less than 5= is greater than or equal to 5>=8 returns false

    23

  • 8/7/2019 MOdule Recovered

    24/78

  • 8/7/2019 MOdule Recovered

    25/78

    are identical in every way, except how they handle errors. Theinclude() function generates a warning (but the script will continueexecution) while the require() function generates a fatal error (and thescript execution will stop after the error).

    These two functions are used to create functions, headers, footers, or

    elements that can be reused on multiple pages.

    This can save the developer a considerable amount of time. Thismeans that you can create a standard header or menu file that youwant all your web pages to include. When the header needs to beupdated, you can only update this one include file, or when you add anew page to your site, you can simply change the menu file (instead ofupdating the links on all web pages).

    The include() Function

    The include() function takes all the text in a specified file and copies itinto the file that uses the include function.

    Example 1

    Assume that you have a standard header file, called "header.php". Toinclude the header file in a page, use the include() function, like this:

    Welcome to my home page

    Some text

    Example 2

    Now, let's assume we have a standard menu file that should be usedon all pages (include files usually have a ".php" extension). Look at the"menu.php" file below:

    25

  • 8/7/2019 MOdule Recovered

    26/78

    Home |About Us |

    Contact Us

    The three files, "default.php", "about.php", and "contact.php" shouldall include the "menu.php" file. Here is the code in "default.php":

    Welcome to my home page

    Some text

    If you look at the source code of the "default.php" in a browser, it willlook something like this:

    Home |About Us |Contact UsWelcome to my home page

    Some text

    And, of course, we would have to do the same thing for "about.php"and "contact.php". By using include files, you simply have to updatethe text in the "menu.php" file if you decide to rename or change theorder of the links or add another web page to the site.

    The require() Function

    The require() function is identical to include(), they only handle errorsdifferently.

    The include() function generates a warning (but the script will continue

    execution) while the require() function generates a fatal error (and thescript execution will stop after the error).

    If you include a file with the include() function and an error occurs,you might get an error message like the following.

    26

  • 8/7/2019 MOdule Recovered

    27/78

    Error message:

    Warning: include(wrongFile.php) [function.include]:failed to open stream:No such file or directory in C:\home\website\test.php on line 5

    Warning: include() [function.include]:Failed opening 'wrongFile.php' for inclusion(include_path='.;C:\php5\pear')in C:\home\website\test.php on line 5

    Hello World!

    Notice that the echo statement is still executed! This is because aWarning does not stop the script execution.

    Now, let's run the same example with the require() function.

    Error message:

    Warning: require(wrongFile.php) [function.require]:failed to open stream:No such file or directory in C:\home\website\test.php on line 5

    Fatal error: require() [function.require]:

    27

  • 8/7/2019 MOdule Recovered

    28/78

    Failed opening required 'wrongFile.php'(include_path='.;C:\php5\pear')

    in C:\home\website\test.php on line 5

    The echo statement was not executed because the script executionstopped after the fatal error.

    It is recommended to use the require() function instead of include(),because scripts should not continue executing if files are missing ormisnamed.

    MODULE 10

    (PHP Functions)

    What are PHP Functions

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

    28

  • 8/7/2019 MOdule Recovered

    29/78

    it.

    Creating PHP functions:

    All functions start with the word "function()"

    Name the function - It should be possible to understand what

    the function does by its name. The name can start with a letteror underscore (not a number)

    Add a "{" - The function code starts after the opening curlybrace

    Insert the function code

    Add a "}" - The function is finished by a closing curly brace

    Example

    A simple function that writes my name when it is called:

    Use a PHP Function

    Now we will use the function in a PHP script:

  • 8/7/2019 MOdule Recovered

    30/78

    ?>

    The output of the code above will be:

    Hello world!My name is Kai Jim Refsnes.

    That's right, Kai Jim Refsnes is my name.

    PHP Functions - Adding parameters to Functions

    Our first function (writeMyName()) is a very simple function. It onlywrites a static string.

    To add more functionality to a function, we can add parameters. Aparameter is just like a variable.

    You may have noticed the parentheses after the function name, like:writeMyName(). The parameters are specified inside the parentheses.

    Example 1

    The following example will write different first names, but the samelast name:

    The output of the code above will be:

    My name is Kai Jim Refsnes.

    30

  • 8/7/2019 MOdule Recovered

    31/78

    My name is Hege Refsnes.

    My name is Stale Refsnes.

    Example 2

    The following function has two parameters:

    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 Functions - Return values

    Functions can also be used to return values.

    Example:

    31

  • 8/7/2019 MOdule Recovered

    32/78

    The output of the code above will be:

    1 + 16 = 17

    PHP Date / Time Functions

    Function Description

    checkdate() Validates a Gregorian date

    date_default_timezone_ Returns the default time zone

    date_default_timezone_sSets the default time zone

    date_sunrise() Returns the time of sunrise for a given day /location

    date_sunset() Returns the time of sunset for a given day /location

    date() Formats a local time/date

    getdate() Returns an array that contains date and timeinformation for a Unix timestamp

    gettimeofday() Returns an array that contains current timeinformation

    gmdate() Formats a GMT/UTC date/time

    gmmktime() Returns the Unix timestamp for a GMT date

    gmstrftime() Formats a GMT/UTC time/date according tolocale settings

    idate() Formats a local time/date as integer

    localtime() Returns an array that contains the timecomponents of a Unix timestamp

    32

  • 8/7/2019 MOdule Recovered

    33/78

    microtime() Returns the microseconds for the current time

    mktime() Returns the Unix timestamp for a date

    strftime() Formats a local time/date according to localesettings

    strptime() Parses a time/date generated with strftime()

    strtotime() Parses an English textual date or time into aUnix timestamp

    time() Returns the current time as a Unix timestamp

    PHP HTTP Functions

    Function Descriptionheader() Sends a raw HTTP header to a client

    headers_list() Returns a list of response headers sent (orready to send)

    headers_sent() Checks if / where the HTTP headers have beensent

    setcookie() Sends an HTTP cookie to a client

    setrawcookie() Sends an HTTP cookie without URL encodingthe cookie value

    PHP Mail Functions

    Function Description

    ezmlm_hash() Calculates the hash value needed by theEZMLM mailing list system

    mail() Allows you to send emails directly from a

    PHP Math Functions

    Function Description

    abs() Returns the absolute value of a number

    acos() Returns the arccosine of a number

    acosh() Returns the inverse hyperbolic cosine of anumber

    asin() Returns the arcsine of a number

    33

  • 8/7/2019 MOdule Recovered

    34/78

    asinh() Returns the inverse hyperbolic sine of anumber

    atan() Returns the arctangent of a number as anumeric value between -PI/2 and PI/2radians

    atan2() Returns the angle theta of an (x,y) point asa numeric value between -PI and PI

    atanh() Returns the inverse hyperbolic tangent of anumber

    base_convert() Converts a number from one base toanother

    bindec() Converts a binary number to a decimalnumber

    ceil() Returns the value of a number roundedupwards to the nearest integer

    cos() Returns the cosine of a number

    cosh() Returns the hyperbolic cosine of a number

    decbin() Converts a decimal number to a binarynumber

    dechex() Converts a decimal number to ahexadecimal number

    decoct() Converts a decimal number to an octalnumber

    deg2rad() Converts a degree to a radian number

    exp() Returns the value of Exexpm1() Returns the value of Ex - 1

    floor() Returns the value of a number roundeddownwards to the nearest integer

    fmod() Returns the remainder (modulo) of thedivision of the arguments

    getrandmax() Returns the maximum random number thatcan be returned by a call to the rand()function

    hexdec() Converts a hexadecimal number to a

    decimal number

    hypot() Returns the length of the hypotenuse of aright-angle triangle

    is_finite() Returns true if a value is a finite number

    is_infinite() Returns true if a value is an infinite number

    is_nan() Returns true if a value is not a number

    34

  • 8/7/2019 MOdule Recovered

    35/78

    lcg_value() Returns a pseudo random number in therange of (0,1)

    log() Returns the natural logarithm (base E) of anumber

    log10() Returns the base-10 logarithm of a number

    log1p() Returns log(1+number)max() Returns the number with the highest value

    of two specified numbers

    min() Returns the number with the lowest valueof two specified numbers

    mt_getrandmax() Returns the largest possible value that canbe returned by mt_rand()

    mt_rand() Returns a random integer using MersenneTwister algorithm

    mt_srand() Seeds the Mersenne Twister random

    number generator

    octdec() Converts an octal number to a decimalnumber

    pi() Returns the value of PI

    pow() Returns the value of x to the power of y

    rad2deg() Converts a radian number to a degree

    rand() Returns a random integer

    round() Rounds a number to the nearest integer

    sin() Returns the sine of a number

    sinh() Returns the hyperbolic sine of a number

    sqrt() Returns the square root of a number

    srand() Seeds the random number generator

    tan() Returns the tangent of an angle

    tanh() Returns the hyperbolic tangent of an angle

    PHP String Functions

    Function Description

    addcslashes() Returns a string with backslashes in frontof the specified characters

    addslashes() Returns a string with backslashes in frontof predefined characters

    bin2hex() Converts a string of ASCII characters tohexadecimal values

    chop() Alias of rtrim()

    35

  • 8/7/2019 MOdule Recovered

    36/78

    chr() Returns a character from a specified ASCIIvalue

    chunk_split() Splits a string into a series of smaller parts

    convert_cyr_string() Converts a string from one Cyrillic

    character-set to anotherconvert_uudecode() Decodes a uuencoded string

    convert_uuencode() Encodes a string using the uuencodealgorithm

    count_chars() Returns how many times an ASCIIcharacter occurs within a string and returnsthe information

    crc32() Calculates a 32-bit CRC for a string

    crypt() One-way string encryption (hashing)

    echo() Outputs strings

    explode() Breaks a string into an array

    fprintf() Writes a formatted string to a specifiedoutput stream

    get_html_translation_table()Returns the translation table used byhtmlspecialchars() and htmlentities()

    hebrev() Converts Hebrew text to visual text

    hebrevc() Converts Hebrew text to visual text andnew lines (\n) into

    html_entity_decode() Converts HTML entities to characters

    htmlentities() Converts characters to HTML entities

    htmlspecialchars_decode() Converts some predefined HTML entities tocharacters

    htmlspecialchars() Converts some predefined characters toHTML entities

    implode() Returns a string from the elements of anarray

    join() Alias of implode()

    levenshtein() Returns the Levenshtein distance betweentwo strings

    localeconv() Returns locale numeric and monetaryformatting information

    ltrim() Strips whitespace from the left side of astring

    md5() Calculates the MD5 hash of a string

    md5_file() Calculates the MD5 hash of a file

    36

  • 8/7/2019 MOdule Recovered

    37/78

    metaphone() Calculates the metaphone key of a string

    money_format() Returns a string formatted as a currencystring

    nl_langinfo() Returns specific local information

    nl2br() Inserts HTML line breaks in front of eachnewline in a string

    number_format() Formats a number with grouped thousands

    ord() Returns the ASCII value of the firstcharacter of a string

    parse_str() Parses a query string into variables

    print() Outputs a string

    printf() Outputs a formatted string

    quoted_printable_decode() Decodes a quoted-printable stringquotemeta() Quotes meta characters

    rtrim() Strips whitespace from the right side of astring

    setlocale() Sets locale information

    sha1() Calculates the SHA-1 hash of a string

    sha1_file() Calculates the SHA-1 hash of a file

    similar_text() Calculates the similarity between twostrings

    soundex() Calculates the soundex key of a string

    sprintf() Writes a formatted string to a variable

    sscanf() Parses input from a string according to aformat

    str_ireplace() Replaces some characters in a string (case-insensitive)

    str_pad() Pads a string to a new length

    str_repeat() Repeats a string a specified number oftimes

    37

  • 8/7/2019 MOdule Recovered

    38/78

    MODULE 11

    (PHP Classes)

    Introduction

    Continuing our PHP functions article, we move on to creating classes.Let me say right at the start that you can write perfectly effective anduseful PHP code without creating classes or going into object orientedprogramming. Another thing is that PHP, at its core, is not an objectoriented language. This is because PHP was built from the C language,which is at its core a procedural language, rather than a methodicalone. However, object oriented programming can be very powerful and

    PHP programmers are increasingly taking advantage of thesecapabilities, which have been greatly expanded since PHP4.

    What is a class?

    A class is a collection of variables and functions that serves a commonpurpose. It gives you the ability to think about real world objects andtranslate them into code. For example, let's try to describe a car.The class "car" might have variables: $name_of_car, $wheels,

    38

  • 8/7/2019 MOdule Recovered

    39/78

    $steeringwheel, $windscreen, $lights, $pedals and $brakes. Thefunctions of a car might include Turnleft(),Turnright() andAccelerate(). The function "Accelerate()" might take arguments suchas $increase_speed. Now, all of the above describes a car and what acar does in both real terms and in code.

    Now you might ask, couldn't this be done with regular functions andvariables? Yes, it could, especially if you were talking about one car.But if you are talking about more than one car, then it would beimpossible to keep up with all the various variables and functionsassociated with multiple cars. This is where classes become veryuseful, because classes bring all those variables and functions underone name. In this case, it's an object named "car." Now if you havemore than one car, all you have to do is instantiate that object. Theterm instantiate basically means making a copy of the object. The newcopy will have all the variables and functions of the original objectavailable to it. You can include the class in any script that you create;the class will work the same

    A class has the following members:

    Attributes

    Methods

    A good example of a class is Human. A human class would havecharacteristics (attributes) of gender, hands, legs, age, and so forth. Itwould also have actions (methods) such as walking, eating, running,talking, and so on.

    The syntax of a class is as follows:

    class class_name{

    var $variable_name;

    functionfunction_name(){

    statements;

    }

    }

    Notice that within the class you use the var keyword to identify yourvariables. At this point you can also assign a value to your variables.Try to use the same naming conventions as you would for functions. Itis easier to recognize what a class is if it reflects its purpose(e.g. classHuman_class{). Another keyword, $this, is used to refer to the

    39

  • 8/7/2019 MOdule Recovered

    40/78

    instances of an object and its attributes e.g. $this->$variable_name.To instantiate a class means to create a new version of it. Say wehave a class called dog, to instantiate it, we do this:

    $rex = new dog();

    Now, rex will have all the attributes of the class dog.

    Creating a Class

    Let's create a simple class to demonstrate the conceptsdiscussed above. Create a new PHP document calledsample_class.php. Our class is going to be called human.We know that a human has legs and arms, which in our class aregoing to represent the attributes. And we also know that humanswalk, eat and sleep. These will act as the methods.

    Script: sample_class.php:

    Here we have a new object created from our human class, called jude.We also have a simple result saying how many legs Jude has. Notehow the variable "legs"(declared in the class) is used without the dollarsign in the echo statement.

    As well as calling attributes, we can also modify the attributes in thesame way. For example if we want the leg attribute to be increased bysay, one, so that legs now equals three, then this is what we do:

    40

  • 8/7/2019 MOdule Recovered

    41/78

    OUTPUT:

    Jude has 3 legs

    As you can see, we can use attributes in a way that is similar tohow we use variables.

    Adding an Attribute to the Objects

    Let' create another instance to see what happens:

    Output:

    Jude has 3 Legs

    Jane has 2 Legs

    As you can see from the result, we can modify the instance of a classwithout touching the class definition itself. This re-usability is whatmakes classes so useful.

    Now we can also add a new attribute to any of the objects (jane orjude). For example, let's add a new attribute to jane. The attribute ishair color:

  • 8/7/2019 MOdule Recovered

    42/78

  • 8/7/2019 MOdule Recovered

    43/78

    The " $this->hcolor=$hcolor;" line will install the hcolor variable as anattribute when a new object is instantiated. So, instead of creating thehair color attribute every time we instantiate a new object, it isautomatically called. The new class will look like this:

    43

  • 8/7/2019 MOdule Recovered

    44/78

    MODULE 12(Cookies)

    What is a Cookie?

    A cookie is often used to identify a user. A cookie is a small file thatthe server embeds on the user's computer. Each time the samecomputer requests a page with a browser, it will send the cookie too.With PHP, you can both create and retrieve cookie values.

    Syntax:

    PHP cookies can be set using the setcookie() function. The syntax is asfollows:

    setcookie(name[, value[, expire[, path[, domain[, security]]]]])

    [name] The cookie name. The name of each cookie sent isstored in the superglobal array $_COOKIE.

    44

  • 8/7/2019 MOdule Recovered

    45/78

    [value] The cookie value. It is associated with the cookiename.

    [expire] The time after which the cookie should expire inseconds

    [path] Specifies the exact path on the domain that can use thecookies.

    [domain] The domain that the cookie is available. If notdomain is specified, the default value is the value of the domainin which cookie was created.

    [security] Specifies whether the cookie will be sent via HTTPS.A value of 1 specifies that the cookie is sent over a secureconnection but it doesn't mean that the cookie is secure. It'sjust a text file like every other cookie. A value of 0 denotes astandard HTTP transmission.

    Example:

    Note: The value of the cookie is automatically URLencoded whensending the cookie, and automatically decoded when received (toprevent URLencoding, use setrawcookie() instead).

    How to Retrieve a Cookie Value?

    The PHP $_COOKIE variable is used to retrieve a cookie value.

    In the example below, we retrieve the value of the cookie named"user" and display it on a page:

    In the following example we use the isset() function to find out if acookie has been set:

  • 8/7/2019 MOdule Recovered

    46/78

    if (isset($_COOKIE["user"]))echo "Welcome " . $_COOKIE["user"] . "!
    ";

    elseecho "Welcome guest!
    ";

    ?>

    How to Delete a Cookie?

    When deleting a cookie you should assure that the expiration date is inthe past.

    Delete example:

    MODULE 13

    (Session)

    What is PHP Session Variable

    A PHP session variable is used to store information about, or changesettings for a user session. Session variables hold information aboutone single user, and are available to all pages in one application.

    When you are working with an application, you open it, do somechanges and then you close it. This is much like a Session. Thecomputer knows who you are. It knows when you start the applicationand when you end. But on the internet there is one problem: the webserver does not know who you are and what you do because the HTTPaddress doesn't maintain state.

    A PHP session solves this problem by allowing you to store user

    46

  • 8/7/2019 MOdule Recovered

    47/78

    information on the server for later use (i.e. username, shopping items,etc). However, session information is temporary and will be deletedafter the user has left the website. If you need a permanent storageyou may want to store the data in a database.

    Sessions work by creating a unique id (UID) for each visitor and store

    variables based on this UID. The UID is either stored in a cookie or ispropagated in the URL.

    Starting a PHP Session

    Before you can store user information in your PHP session, you mustfirst start up the session.

    Note: The session_start() function must appear BEFORE the tag:

    The code above will register the user's session with the server, allowyou to start saving user information, and assign a UID for that user'ssession.

    Storing a Session Variable

    The correct way to store and retrieve session variables is to use thePHP $_SESSION variable:

    47

  • 8/7/2019 MOdule Recovered

    48/78

    Output:

    Pageviews=1

    In the example below, we create a simple page-views counter. Theisset() function checks if the "views" variable has already been set. If"views" has been set, we can increment our counter. If "views" doesn'texist, we create a "views" variable, and set it to 1:

    Destroying a Session

    If you wish to delete some session data, you can use the unset() orthe session_destroy() function.

    The unset() function is used to free the specified session variable:

    You can also completely destroy the session by calling thesession_destroy() function:

    Note: session_destroy() will reset your session and you will lose allyour stored session data.

    48

  • 8/7/2019 MOdule Recovered

    49/78

    MODULE 14

    (File Handling)

    This module describes file handling in PHP.

    How to Create a File

    The fopen function needs two important pieces of information tooperate correctly. First, we must supply it with the name of the filethat we want it to open. Secondly, we must tell the function what weplan on doing with that file (i.e. read from the file, write information,etc).

    Since we want to create a file, we must supply a file name and tell PHPthat we want to write to the file. Note: We have to tell PHP we arewriting to the file, otherwise it will not create a new file.

    49

  • 8/7/2019 MOdule Recovered

    50/78

    PHP Code:

    $ourFileName = "testFile.txt";$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");fclose($ourFileHandle);

    The file "testFile.txt" should be created in the same directory wherethis PHP code resides. PHP will see that "testFile.txt" does not existand will create it after running this code. There's a lot of information inthose three lines of code, let's make sure you understand it.

    $ourFileName = "testFile.txt";

    Here we create the name of our file, "testFile.txt" and store itinto a PHP String variable $ourFileName.

    $ourFileHandle = fopen($ourFileName, 'w') or die("can'topen file");

    This bit of code actually has two parts. First we use the functionfopen and give it two arguments: our file name and we informPHP that we want to write by passing the character "w".

    Second, the fopen function returns what is called a file handle,which will allow us to manipulate the file. We save the filehandle into the $ourFileHandle variable. We will talk more aboutfile handles later on.

    fclose($ourFileHandle);

    We close the file that was opened. fclose takes the file handlethat is to be closed. We will talk more about this more in the fileclosing lesson.

    PHP - Permissions

    If you are trying to get this program to run and you are having errors,you might want to check that you have granted your PHP fileaccess to write information to the hard drive. Setting permissionsis most often done with the use of an FTP program to execute acommand called CHMOD. Use CHMOD to allow the PHP file to

    write to disk, thus allowing it to create a file.

    Opening a File

    The fopen() function is used to open files in PHP.

    50

    http://www.tizag.com/phpT/strings.phphttp://www.tizag.com/phpT/strings.php
  • 8/7/2019 MOdule Recovered

    51/78

    The first parameter of this function contains the name of the file to beopened and the second parameter specifies in which mode the fileshould be opened in:

    The file may be opened in one of the following modes:

    File Modes Description

    r Read only. File pointer at the start of the file

    r+ Read/Write. File pointer at the start of the file

    w Write only. Truncates the file (overwriting it). If the file doesn't exist,fopen() will try to create the file

    w+ Read/Write. Truncates the file (overwriting it). If the file doesn't exist,fopen() will try to create the file

    a Append. File pointer at the end of the file. If the file doesn't exist, fopen()will try to create the file

    a+Read/Append. File pointer at the end of the file. If the file doesn't exist,fopen() will try to create the file

    x Create and open for write only. File pointer at the beginning of the file. Ifthe file already exists, the fopen() call will fail and generate an error. Ifthe file does not exist, try to create it

    x+ Create and open for read/write. File pointer at the beginning of the file. Ifthe file already exists, the fopen() call will fail and generate an error. Ifthe file does not exist, try to create it

    Note: If the fopen() function is unable to open the specified file, itreturns 0 (false).

    Example

    The following example generates a message if the fopen() function isunable to open the specified file:

    51

  • 8/7/2019 MOdule Recovered

    52/78

    Closing a File

    The fclose() function is used to close a file.

    In PHP it is not system critical to close all your files after using thembecause the server will close all files after the PHP code finishes

    execution. However the programmer is still free to make mistakes(i.e. editing a file that you accidentally forgot to close). You shouldclose all files after you have finished with them because it's a goodprogramming practice and because we told you to!

    fclose($f);

    EXAMPLE:

    $ourFileName = "testFile.txt";$ourFileHandle = fopen($ourFileName, 'w') or die("can't openfile");

    fclose($ourFileHandle);

    The function fclose requires the file handle that we want to close down.In our example we set our variable "$fileHandle" equal to the filehandle returned by the fopen function.

    After a file has been closed down with fclose it is impossible to read,write or append to that file unless it is once more opened up with thefopen function.

    Writing to a file

    Now that you know how to open and close a file, lets get on to themost useful part of file manipulation, writing! There is really only onemain function that is used to write and it's logically called fwrite.Before we can write information to our test file we have to use thefunction fopen to open the file for writing.

    $myFile = "testFile.txt";$fh = fopen($myFile, 'w');

    We can use php to write to a text file. The fwrite function allows datato be written to any type of file. Fwrite's first parameter is the filehandle and its second parameter is the string of data that is to bewritten. Just give the function those two bits of information and you're

    52

  • 8/7/2019 MOdule Recovered

    53/78

  • 8/7/2019 MOdule Recovered

    54/78

    $theData. You could echo this string, $theData, or write it to anotherfile.

    If you wanted to read all the data from the file, then you need to getthe size of the file. The filesize function returns the length of a file, inbytes, which is just what we need! The filesize function requires the

    name of the file that is to be sized up.

    $myFile = "testFile.txt";$fh = fopen($myFile, 'r');$theData = fread($fh, filesize($myFile));fclose($fh);echo $theData;

    The feof() function is used to determine if the end of file is true.

    Note: You cannot read from files opened in w, a, and x mode!

    if (feof($f))echo "End of file";

    Reading a Character

    The fgetc() function is used to read a single character from a file.

    Note: After a call to this function the file pointer has moved to thenext character.

    Example

    The example below reads a file character by character, until the end offile is true:

    Deleting a File

    54

  • 8/7/2019 MOdule Recovered

    55/78

    You know how to create a file. You know how to open a file in anassortment of different ways. You even know how to read and writedata from a file! Now it's time to learn how to destroy (delete) files.In PHP you delete files by calling the unlinkfunction.

    File UnlinkWhen you view the contents of a directory you can see all the files thatexist in that directory because the operating system or application thatyou are using displays a list of filenames. You can think of thesefilenames as links that join the files to the directory you are currentlyviewing. If you unlink a file, you are effectively causing the system toforget about it or delete it!

    Before you can delete (unlink) a file, you must first be sure that it isnot open in your program. Use the fclose function to close down anopen file.

    $myFile = "testFile.txt";$fh = fopen($myFile, 'w') or die("can't open file");fclose($fh);

    Now to delete testFile.txtwe simply run a PHP script that is located inthe same directory. Unlink just needs to know the name of the file tostart working its destructive magic.

    $myFile = "testFile.txt";unlink($myFile);

    Unlink: Safety First!

    With great power comes a slough of potential things you can mess up!When you are performing the unlink function be sure that you aredeleting the right file!

    File Upload: HTML Form

    Before you can use PHP to manage your uploads, you must first buildan HTML form that lets users select a file to upload. See our HTMLForm lesson for a more in-depth look at forms.

    HTML Code:

    Choose a file to upload:

    55

    http://www.tizag.com/htmlT/forms.phphttp://www.tizag.com/htmlT/forms.phphttp://www.tizag.com/htmlT/forms.phphttp://www.tizag.com/htmlT/forms.php
  • 8/7/2019 MOdule Recovered

    56/78

    Here is a brief description of the important parts of the above code:

    enctype="multipart/form-data" - Necessary for our to-be-created PHP file to function properly.

    action="uploader.php" - The name of our PHP page that willbe created, shortly.

    method="POST" - Informs the browser that we want to sendinformation to the server using POST.

    input type="hidden" name="MA... - Sets the maximumallowable file size, in bytes, that can be uploaded. This safetymechanism is easily bypassed and we will show a solid backupsolution in PHP. We have set the max file size to 100KB in thisexample.

    input name="uploadedfile" - uploadedfile is how we willaccess the file in our PHP script.

    Save that form code into a file and call it upload.html. If you view it ina browser it should look like this:

    File Upload: What's the PHP Going to Do?

    Now that we have the right HTML form we can begin to code the PHPscript that is going to handle our uploads. Typically, the PHP file shouldmake a key decision with all uploads: keep the file or throw it away. Afile might be thrown away from many reasons, including:

    The file is too large and you do not want to have it on yourserver. You wanted the person to upload a picture and they uploaded

    something else, like an executable file (.exe). There were problems uploading the file and so you can't keep it.

    This example is very simple and omits the code that would add suchfunctionality.

    File Upload: uploader.php

    When the uploader.php file is executed, the uploaded file exists in a

    temporary storage area on the server. If the file is not moved to adifferent location it will be destroyed! To save our precious file we aregoing to need to make use of the $_FILESassociative array.

    The $_FILES array is where PHP stores all the information about files.There are two elements of this array that we will need to understandfor this example.

    56

    http://www.tizag.com/phpT/arrays.phphttp://www.tizag.com/phpT/arrays.php
  • 8/7/2019 MOdule Recovered

    57/78

    uploadedfile - uploadedfile is the reference we assigned in ourHTML form. We will need this to tell the $_FILES array which filewe want to play around with.

    $_FILES['uploadedfile']['name'] - name contains the originalpath of the user uploaded file.

    $_FILES['uploadedfile']['tmp_name'] - tmp_name contains

    the path to the temporary file that resides on the server. The fileshould exist on the server in a temporary directory with atemporary name.

    Now we can finally start to write a basic PHP upload manager script!Here is how we would get the temporary file name, choose apermanent name, and choose a place to store the file.

    // Where the file is going to be placed$target_path = "uploads/";

    /* Add the original filename to our target path.Result is "uploads/filename.extension" */$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);$_FILES['uploadedfile']['tmp_name'];

    NOTE: You will need to create a new directory in the directory whereuploader.php resides, called "uploads", as we are going to be savingfiles there.

    We now have all we need to successfully save our file to the server.$target_path contains the path where we want to save our file to.

    File Upload: move_uploaded_file Function

    Now all we have to do is call the move_uploaded_file function and letPHP do its magic. The move_uploaded_file function needs to know 1)The path of the temporary file (check!) 2) The path where it is to bemoved to (check!).

    $target_path = "uploads/";

    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$target_path)) {

    echo "The file ". basename( $_FILES['uploadedfile']['name'])." has been uploaded";

    } else{echo "There was an error uploading the file, please try

    again!";}

    57

  • 8/7/2019 MOdule Recovered

    58/78

    If the upload is successful, then you will see the text "The file filenamehas been uploaded". This is because $move_uploaded_file returns trueif the file was moved, and false if it had a problem.

    If there was a problem then the error message "There was an error

    uploading the file, please try again!" would be displayed.

    MODULE 15

    (Introduction to MySQL)

    What is MySQL?

    MySQL is a database. A database defines a structure for storinginformation.

    In a database, there are tables. Just like HTML tables, database tables

    contain rows, columns, and cells.

    Databases are useful when storing information categorically. Acompany may have a database with the following tables: "Employees","Products", "Customers" and "Orders".

    Database Tables

    A database most often contains one or more tables. Each table has a

    58

  • 8/7/2019 MOdule Recovered

    59/78

    name (e.g. "Customers" or "Orders"). Each table contains records(rows) with data.

    Below is an example of a table called "Persons":

    LastName FirstName Address City

    Hansen Ola Timoteivn 10 Sandnes

    Svendson Tove Borgvn 23 Sandnes

    Pettersen Kari Storgt 20 Stavanger

    The table above contains three records (one for each person) and fourcolumns (LastName, FirstName, Address, and City).

    Queries

    A query is a question or a request.

    With MySQL, we can query a database for specific information and have arecordset returned.

    Look at the following query:

    SELECT LastName FROMPersons

    The query above selects all the data in the LastName column in the Personstable, and will return a recordset like this:

    LastName

    Hansen

    Svendson

    Pettersen

    59

  • 8/7/2019 MOdule Recovered

    60/78

    Connecting to a MySQL Database

    Before you can access and work with data in a database, you must create aconnection to the database.

    In PHP, this is done with the mysql_connect() function.

    Syntax

    mysql_connect(servername,username,password);

    Parameter Description

    servername Optional. Specifies the server to connect to.

    Default value is "localhost:3306"

    username Optional. Specifies the username to log in with.Default value is the name of the user that owns

    password Optional. Specifies the password to log in with.Default is ""

    Note: There are more available parameters, but the ones listed above arethe most important. Visit our full PHP MySQL Reference for more details.

    Example

    In the following example we store the connection in a variable ($con) forlater use in the script. The "die" part will be executed if the connection fails:

    60

  • 8/7/2019 MOdule Recovered

    61/78

    Closing a Connection

    The connection will be closed as soon as the script ends. To close theconnection before, use the mysql_close() function.

    A database holds one or multiple tables.

    Create a Database

    The CREATE DATABASE statement is used to create a database in MySQL.

    Syntax

    CREATE DATABASE database_name

    To get PHP to execute the statement above we must use the mysql_query()function. This function is used to send a query or command to a MySQLconnection.

    Example

    In the following example we create a database called "my_db":

    61

  • 8/7/2019 MOdule Recovered

    62/78

    Create a Table

    The CREATE TABLE statement is used to create a database table in MySQL.

    Syntax

    CREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name3 data_type,

    .......)

    We must add the CREATE TABLE statement to the mysql_query() functionto execute the command.

    Example

    The following example shows how you can create a table named "person",with three columns. The column names will be "FirstName", "LastName" and"Age":

    62

  • 8/7/2019 MOdule Recovered

    63/78

    Important: A database must be selected before a table can be created.

    The database is selected with the mysql_select_db() function.

    Note: When you create a database field of type varchar, you must specifythe maximum length of the field, e.g. varchar(15).

    MySQL Data Types

    Below is the different MySQL data types that can be used:

    Numeric Data Description

    int(size)smallint(size)tinyint(size)mediumint(size)bigint(size)

    Hold integers only. The maximum number of digits can bespecified in the size parameter

    63

  • 8/7/2019 MOdule Recovered

    64/78

  • 8/7/2019 MOdule Recovered

    65/78

    Primary Keys and Auto Increment Fields

    Each table should have a primary key field.

    A primary key is used to uniquely identify the rows in a table. Each primary

    key value must be unique within the table. Furthermore, the primary keyfield cannot be null because the database engine requires a value to locatethe record.

    The primary key field is always indexed. There is no exception to this rule!You must index the primary key field so the database engine can quicklylocate rows based on the key's value.

    The following example sets the personID field as the primary key field. Theprimary key field is often an ID number, and is often used with theAUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the

    value of the field by 1 each time a new record is added. To ensure that theprimary key field cannot be null, we must add the NOT NULL setting to thefield.

    Example

    $sql = "CREATE TABLE person(personID int NOT NULL AUTO_INCREMENT,PRIMARY KEY(personID),FirstName varchar(15),LastName varchar(15),Age int

    )";

    mysql_query($sql,$con);

    The INSERT INTO statement is used to insert new records into a databasetable.

    Insert Data Into a Database TableThe INSERT INTO statement is used to add new records to a database table.

    Syntax

    INSERT INTO table_nameVALUES (value1, value2,....)

    65

  • 8/7/2019 MOdule Recovered

    66/78

    You can also specify the columns where you want to insert the data:

    INSERT INTO table_name (column1, column2,...)VALUES (value1, value2,....)

    Note: SQL statements are not case sensitive. INSERT INTO is the same asinsert into.

    To get PHP to execute the statements above we must use themysql_query() function. This function is used to send a query or commandto a MySQL connection.

    Example

    In the previous chapter we created a table named "Person", with three

    columns; "Firstname", "Lastname" and "Age". We will use the same table inthis example. The following example adds two new records to the "Person"table:

  • 8/7/2019 MOdule Recovered

    67/78

    Firstname: Lastname: Age:

    When a user clicks the submit button in the HTML form in the exampleabove, the form data is sent to "insert.php". The "insert.php" file connectsto a database, and retrieves the values from the form with the PHP $_POSTvariables. Then, the mysql_query() function executes the INSERT INTO

    statement, and a new record will be added to the database table.

    Below is the code in the "insert.php" page:

  • 8/7/2019 MOdule Recovered

    68/78

    The SELECT statement is used to select data from a database.

    Select Data From a Database Table

    The SELECT statement is used to select data from a database.

    Syntax

    SELECT column_name(s)FROM table_name

    Note: SQL statements are not case sensitive. SELECT is the same as select.

    To get PHP to execute the statement above we must use the mysql_query()function. This function is used to send a query or command to a MySQLconnection.

    Example

    The following example selects all the data stored in the "Person" table (The* character selects all of the data in the table):

    68

  • 8/7/2019 MOdule Recovered

    69/78

    The example above stores the data returned by the mysql_query() functionin the $result variable. Next, we use the mysql_fetch_array() function toreturn the first row from the recordset as an array. Each subsequent call tomysql_fetch_array() returns the next row in the recordset. The while looploops through all the records in the recordset. To print the value of eachrow, we use the PHP $row variable ($row['FirstName'] and

    $row['LastName']).

    Peter GriffinGlenn Quagmire

    Display the Result in an HTML Table

    The following example selects the same data as the example above, but willdisplay the data in an HTML table:

    The output of the code will be:

    Firstname Lastname

    69

  • 8/7/2019 MOdule Recovered

    70/78

  • 8/7/2019 MOdule Recovered

    71/78

  • 8/7/2019 MOdule Recovered

    72/78

    The output of the code above will be:

    Glenn Quagmire 33Peter Griffin 35

    Sort Ascending or Descending

    If you use the ORDER BY keyword, the sort-order of the recordset is

    ascending by default (1 before 9 and "a" before "p").

    Use the DESC keyword to specify a descending sort-order (9 before 1 and"p" before "a"):

    SELECT column_name(s)FROM table_nameORDER BY column_name DESC

    Order by Two Columns

    It is possible to order by more than one column. When ordering by morethan one column, the second column is only used if the values in the firstcolumn are identical:

    SELECT column_name(s)FROM table_nameORDER BY column_name1, column_name2

    72

  • 8/7/2019 MOdule Recovered

    73/78

    The UPDATE statement is used to modify data in a database table.

    Update Data In a Database

    The UPDATE statement is used to modify data in a database table.

    Syntax

    UPDATE table_nameSET column_name = new_valueWHERE column_name = some_value

    Note: SQL statements are not case sensitive. UPDATE is the same asupdate.

    To get PHP to execute the statement above we must use the mysql_query()function. This function is used to send a query or command to a MySQLconnection.

    Example

    Earlier in the tutorial we created a table named "Person". Here is how it

    FirstName LastName Age

    Peter Griffin 35

    Glenn Quagmire 33

    The following example updates some data in the "Person" table:

  • 8/7/2019 MOdule Recovered

    74/78

    FirstName LastName Age

    Peter Griffin 36

    Glenn Quagmire 33

    The DELETE FROM statement is used to delete rows from a database table.

    Delete Data In a Database

    The DELETE FROM statement is used to delete records from a databasetable.

    Syntax

    DELETE FROM table_nameWHERE column_name = some_value

    Note: SQL statements are not case sensitive. DELETE FROM is the same asdelete from.

    To get PHP to execute the statement above we must use the mysql_query()function. This function is used to send a query or command to a MySQLconnection.

    Example

    Earlier in the tutorial we created a table named "Person". Here is how it

    looks:

    FirstName LastName Age

    Peter Griffin 35

    Glenn Quagmire 33

    The following example deletes all the records in the "Person" table whereLastName='Griffin':

    74

  • 8/7/2019 MOdule Recovered

    75/78

  • 8/7/2019 MOdule Recovered

    76/78

  • 8/7/2019 MOdule Recovered

    77/78

    mysql_field_flags() Returns the flags associated with a field in arecordset

    mysql_field_len() Returns the maximum length of a field in a recordset

    mysql_field_name() Returns the name of a field in a recordset

    mysql_field_seek() Moves the result pointer to a specified field

    mysql_field_table() Returns the name of the table the specified field is in

    mysql_field_type() Returns the type of a field in a recordset

    mysql_free_result() Free result memory

    mysql_get_client_info() Returns MySQL client info

    mysql_get_host_info() Returns MySQL host info

    mysql_get_proto_info() Returns MySQL protocol info

    mysql_get_server_info() Returns MySQL server infomysql_info() Returns information about the last query

    mysql_insert_id() Returns the AUTO_INCREMENT ID generated fromthe previous INSERT operation

    mysql_list_dbs() Lists available databases on a MySQL server

    mysql_list_fields() Deprecated. Lists MySQL table fields. Usemysql_query() instead

    mysql_list_processes() Lists MySQL processes

    mysql_list_tables() Deprecated. Lists tables in a MySQL database. Usemysql_query() instead

    mysql_num_fields() Returns the number of fields in a recordset

    mysql_num_rows() Returns the number of rows in a recordset

    mysql_pconnect() Opens a persistent MySQL connection

    mysql_ping() Pings a server connection or reconnects if there is noconnection

    mysql_query() Executes a query on a MySQL database

    mysql_real_escape_string()

    Escapes a string for use in SQL statements

    mysql_result() Returns the value of a field in a recordset

    mysql_select_db() Sets the active MySQL database

    mysql_stat() Returns the current system status of the MySQLserver

    77

  • 8/7/2019 MOdule Recovered

    78/78

    mysql_tablename() Deprecated. Returns the table name of field. Usemysql_query() instead

    mysql_thread_id() Returns the current thread ID

    mysql_unbuffered_query()

    Executes a query on a MySQL database (withoutfetching / buffering the result)