Category Archives: Internet Programming

PHP Functions, Arrays, Databases, Email & Sessions

Published by:

User defined PHP Functions

  • Before the <head> section.
  • In the <head> … </head> section
  • In the <body> … </body> section
    &lt;?php
    
    function before_head()
    
    {
    
    echo &quot;before head&lt;br&gt;&quot;;
    
    }
    
    ?&gt;
    
    &lt;html&gt;
    
    &lt;head&gt;
    
    &lt;?php
    
    function in_head()
    
    {
    
    echo &quot;in head&lt;br&gt;&quot;;&lt;/li&gt;
    &lt;/ul&gt;
    }
    
    ?&gt;
    
    &lt;/head&gt;
    
    &lt;body&gt;
    
    &lt;?php
    
    function in_body()
    
    {
    
    echo &quot;in_body()&lt;br&gt;&quot;;
    
    }
    
    ?&gt;
    
    &lt;?php
    
    before_head();
    
    in_head();
    
    in_body();
    
    ?&gt;
    
    &lt;/body&gt;
    
    &lt;/html&gt;
    
    

    External PHP Functions

    
    &lt;?php
    
    include &quot;testfuncs.inc&quot;;
    
    ?&gt;
    
    &lt;html&gt;
    
    &lt;head&gt;
    
    &lt;/head&gt;
    
    &lt;body&gt;
    
    &lt;?php
    
    loop(9);
    
    ?&gt;
    
    &lt;/body&gt;
    
    &lt;/html&gt;
    
    &lt;?php
    
    include &quot;header.inc&quot;;
    
    include &quot;body.inc&quot;;
    
    ?&gt;
    
    

    Returning Values from Functions

    • Use the return keyword followed by the variable or value you want to return from the function.
    • 
      &lt;?php
      
      function circle_area($radius)
      
      {
      
      return(M_PI * pow($radius,2));
      
      }
      
      ?&gt;
      
      

    PHP Arrays

    • A list of key or value elements in which any number of values can be stored.
    • Two types of arrays in PHP – indexed and associative.
    • Indexed arrays– The key or index to each value is an integer.
      &lt;?php
      
      $names=array(&quot;Bob&quot;,&quot;Carla&quot;,&quot;Danny&quot;);
      
      $food[]=&quot;eggs&quot;, $food[]=&quot;milk&quot;;
      
      echo &quot;&lt;table border='2'&gt;&quot;;
      
      for($i=0;$i&lt;count($names);$i++)
      
      {
      
      ?&gt;
      &lt;tr&gt;&lt;td&gt;
      &lt;?php
      
      print $names[$i].&quot;&lt;/td&gt;&lt;td&gt;&quot;;
      
      print $food[$i].&quot;&lt;/td&gt;&lt;/tr&gt;&quot;;
      
      }
      
      ?&gt;
      
      &lt;/table&gt;
      
      &lt;/body&gt;
      
      &lt;/html&gt;
      
      
    • Associative arrays – Members of associative arrays are accessed by means of text strings. The key or index to each value is a string.
    • 
      $composers=array('German'=&gt;'Beethoven', 'French' =&gt; 'Mendelssohn', 'English' =&gt; 'Elgar', 'Russian' =&gt; 'Rachmaninov');
      
      

    Accessing the Elements of an Associative Array

    • Elements can be accessed easily by means of their key.
    • &lt;?php
      
      $composers=array('German'=&gt;'Beethoven', 'French' =&gt; 'Mendelssohn', 'English' =&gt; 'Elgar', 'Russian' =&gt; 'Rachmaninov');
      
      while ($result = each($composers))
      
      {
      
      print $result[0].&quot; &quot;.$result[1];
      
      print &quot;&lt;br&gt;&quot;;
      
      }
      
      // reset to the start of the array
      
      reset($composers);
      
      while($result = each($composers))
      
      {
      
      print $result[0].&quot; &quot;.$result[1];
      
      print &quot;&lt;br&gt;&quot;;
      }
      
      ?&gt;
      
      

    The foreach() function

    • Incorporates a loop and traverses the whole array it is applied to.
    • Takes two arguments.
    • First argument – the name of the array to be traversed.
    • Second argument – the name of the variable to hold the individual element.
    • Can be applied to multidimensional arrays and associative arrays as well as indexed arrays.
      &lt;?php
      $composers=array('German'=&gt;'Beethoven', 'French' =&gt; 'Mendelssohn', 'English' =&gt; 'Elgar', 'Russian' =&gt; 'Rachmaninov');
      
      echo &quot;&lt;table broder='1'&gt;&quot;;
      
      foreach($composers as $name)
      
      {
      
      print &quot;&lt;tr&gt;&lt;td&gt;&quot;;
      
      print $name;
      
      print &quot;&lt;/td&gt;&lt;/tr&gt;&quot;;
      
      }
      
      echo &quot;&lt;/table&gt;&lt;br&gt;&quot;;
      
      reset ($composers);
      
      echo &quot;&lt;table border='1'&gt;&quot;;
      
      foreach($composers as $nation=&gt;$name)
      
      {
      
      print &quot;&lt;tr&gt;&lt;td&gt;&quot;;
      
      print $nation;
      
      print &quot;&lt;/td&gt;&lt;td&gt;&quot;;
      
      print $name;
      
      print &quot;&lt;/td&gt;&lt;/tr&gt;&quot;;
      
      }
      
      echo &quot;&lt;/table&gt;&lt;br&gt;&quot;;
      
      ?&gt;
      

    PHP & MySQL

    • mysql_connect – Connect to MySQL Server
    • mysql_select_db – Select the database to use
    • mysql_close – Close a MySQL connection
    • mysql_change_user – Changes the identity of the logged in user with an active connection.

    PHP Constant

    • define() function – create named data items whose values cannot be changed.

    Creating & Dropping Databases in PHP

    • mysql_create_db and mysql_drop_db

    MySQL Queries using PHP

    • mysql_query(query_string,[connection]) – execute mysql commands inside PHP scripts.

    Processing the Results Associative Array

    • We can print out the columns in any order as well as conveniently deciding what columns to print.
      $num_rows=mysql_num_rows($result);
      
      if($num_rows &gt; 0) {
      
      print &quot;&lt;table border='1'&gt;&quot;;
      
      while ($a_row=mysql_fetch_assoc($result)) {
      
      print &quot;&lt;tr&gt;n&quot;;
      
      print &quot;&lt;td&gt;$a_row[title]&lt;/td&gt;&quot;;
      
      print &quot;&lt;td&gt;$a_row[author_lastname]&lt;/td&gt;&quot;;
      
      print &quot;&lt;td&gt;$a_row[author_firstname]&lt;/td&gt;&quot;;
      
      print &quot;&lt;/tr&gt;&quot;;
      
      }
      
      print &quot;&lt;/table&gt;&quot;;
      
      }
      

    PHP functions & Returning Information with MySQL

    • mysql_list_dbs – Returns a list of databases available on the server.
    • mysql_list_tables – Returns a list of tables in a database.
    • mysql_field_ien – Returns the length of a specified field.
    • mysql_field_table – Gets the name of the table containing the specified field.

    Sending Email from PHP

    • mail() function
      mail($address,$subject,$message);
      
      &lt;?php
      
      $address=&quot;&lt;a href=&quot;mailto:abc@example.com&quot;&gt;abc@example.com&lt;/a&gt;&quot;;
      
      $subject=&quot;Testing&quot;;
      
      $message=&quot;This is a test email&quot;;
      
      mail($address,$subject,$message);
      
      ?&gt;
      

    Understanding Sessions

    • Arrays: Associative and indexed
    • Server $_GET,$_POST and $_REQUEST arrays, also the $_SESSION array.
    • The session data is stored in a file that can only be read by the user running the server.
    • Every session has a unique session id.
    • The stored session data is stored in a special format inside the file.
    • When the session_start() is called the file is created but is empty.
    • Calling session_unreg() deletes the session file.
    • Sessions normally use cookies to store the session id on the client side.
    • The location of the session files is set by the PHP configuration file (php.ini) which uses the directive session.save_path to set it.

    PHP Sessions

    • session_start() – Initialises a new session or resume an existing one.
    • session_register() – Registers variables with a session.
    • empty() – Returns true if a variable is undefined or empty.
    • isset() – Checks to see if a php variable has a value other than NULL.

Introduction to PHP

Published by:

What is PHP?

  • PHP code is embedded within HTML pages for server side execution.
  • Commonly used to extract data out of a database and present it on the Web page.
  • A server-side interpreted scripting language used to enhance the capabilities of Web Pages.
  • Open source product.
  • Can be installed to run on Unix and Windows.
  • Can run with either the Apache web server or the Microsoft IIS Web server.
  • Derives it’s syntax from the C programming language.
  • Syntax such as for loops and conditional tests is identical to that in javascript and java.
  • PHP variable names begin with the $ symbol (similar as Perl).

Printing in PHP


&lt;?php

print (
&quot;Hello World&quot;);
echo (&quot;Hello World&quot;);
$test = &quot;Hello World&quot;;
printf(&quot;%s&lt;br&gt;&quot;,$test);
?&gt;

printf Function

  • Similar to the C function
  • Facilitates the formatted output of data
  • The format of variable types is set by means of a conversion specification or format string.
  • Useful for printing floating point numbers to a specific number of decimal places.
  • Pad out strings with spaces.

     

Functions in PHP


&lt;?php

function printoutput($data)

{

echo $data.&quot;&lt;br&gt;&quot;;

}

$name=&quot;John Smith&quot;;

printoutput($name);

?&gt;

Generating HTML using PHP

&lt;html&gt;
&lt;body&gt;
&lt;?php
echo &quot;&lt;p style=&quot;color:blue”;&gt;&quot;;
echo &quot;Testing&quot;;
echo &quot;&lt;/p&gt;&quot;;
?&gt;
&lt;/body&gt;
&lt;/html&gt;

Arrays in PHP

  • Flexible
  • Arrays can be multidimensional.
  • Can store different data types.
  • Can be set up so elements are accessed by an index number – indexed array.
  • Can be set up so elements are accessed by a string – associative array

 

Indexed Array

  • Indexed arrays have an integer subscript.
&lt;?php
$characters=array(&quot;Andre&quot;, &quot;Benny&quot;, &quot;Christopher&quot;);
echo $characters[0].&quot;&lt;br&gt;&quot;;
echo $characters[1].&quot;&lt;br&gt;&quot;;
echo $characters[2].&quot;&lt;br&gt;&quot;;
?&gt;
  • Contents of the array can have different datatypes
&lt;?php
$data=array(&quot;Test&quot;,123,99.999);
echo $data[0].&quot;&lt;br&gt;&quot;;
echo $data[1].&quot;&lt;br&gt;&quot;;
echo $data[2].&quot;&lt;br&gt;&quot;;
?&gt;

 

Associative Arrays

  • Allow access to the array elements using a string rather than an index number.
  • Useful when processing the results of an SQL enquiry.
&lt;?php
$person[&quot;name&quot;]=&quot;Catherine&quot;;
$person[&quot;occupation&quot;]=&quot;waitress&quot;;
echo &quot;Name = &quot;.$person[&quot;name&quot;].&quot;&lt;br&gt;&quot;;
echo &quot;Occupation = &quot;.$person[&quot;occupation&quot;].&quot;&lt;br&gt;&quot;;
?&gt;

 

Passing Data from the Browser to the Server

  • User data is passed from HTML web pages to the server using forms.
  • The method used to send the data is specified as an attribute of the <form> tag.
  • Two methods available – get and post.
  • Get method – Appends the names of the variables after the URL.
  • Post method – passes the data separately from the URL.

Sending Data via a Form


&lt;form method=&quot;get&quot; action=&quot;procform.php&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;var1&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;var2&quot;&gt;
&lt;input type=&quot;submit&quot; value=&quot;Submit data&quot;&gt;
&lt;/form&gt;

Passing Variables into Server-side Scripts

  • Data passed using the get method is stored in an associative array called $_GET. The index into the array is the variable name.
  • A similar array ($_POST) is used for data submitted by the post method.
  • The $_REQUEST array can be used instead of $_GET or $_POST. It contains both GET and POST data.
&lt;?php
echo $_GET[&quot;var1&quot;].&quot;&lt;br&gt;&quot;;
$v1=$_GET[&quot;var1&quot;];
echo $v1.&quot;&lt;br&gt;&quot;;
?&gt;

Using $_REQUEST

  • To access the form data.
&lt;?php
echo $_REQUEST[&quot;var1&quot;].&quot;&lt;br&gt;&quot;;
$v1=$_REQUEST[&quot;var1&quot;];
echo $v1.&quot;&lt;br&gt;&quot;;
?&gt;

Hyperlink with GET variables

  • When the PHP script is called by the web server, it receives the 2 GET variables.
&lt;a href=&quot;procform1.php?var1=Test&amp;var2=Me&quot;&gt;Click me&lt;/a&gt;

Selecting MySQL table data by using PHP


&lt;?php
// connect to the server with the credentials else print the error.
$link = mysql_connect(&quot;john&quot;, &quot;nancy&quot;,&quot;password&quot;)
or die (&quot;Unable to connect to server: &quot;.mysql_error());
// connect to the database else pring the error.
mysql_select_db(&quot;testdb&quot;,$link);
or die(&quot;Unable to connect to database: &quot;.mysql_error();
$result = mysql_query(&quot;select * from tblroutes where price &lt; 250&quot;);
$num_rows=mysql_num_rows($result);
echo $num_rows;

mysql_close($link);
?&gt;

Sessions

  • Stateless Protocol – When a page is retrieved through a web server, once the page has been sent, the Web Server does not retain any knowledge about the retrieval.
  • When a PHP script that retrieves information from a database ends, the retrieved data as well as the script’s own variables are lost forever.

PHP Methods to Create Persistent Data

  • Two main methods available whereby data can be saved:
    • Cookies
    • Sessions

Sessions

  • Store variable names and their values
  • Store the data in a file on the server.
  • The default place where the data is stored is in /tmp for Unix. The location is set by the php.ini file.
  • Sessions are created and resumed by using the session_start() function.
  • Sessions are destroyed using the session_destroy() function.
  • Variables (including arrays) are registered by using the session_register(variable_name) function.

Testing Variables

  • isset($x) – test whether the variable exists – return true if it exists.
  • empty($x) – test if the variable is empty – return true if it’s empty.

Cascading Select

Published by:

  • Structure – defines the components and areas on the page. This includes the head, body, title, links, tables, forms and divs.
  • Presentation – the way the information is presented, such as its colour, size, background colour, font, etc.

Style Sheet Structure

p {font-size: 12 pt;
font-face: courier; }
selector {property: value }

–
Declaration
–
Style Sheet Rule

Four Style Sources

  • External
    • Imported
    • Linked
  • Internal
    • Embedded
    • Inline

Cascading

  • Determines the precedence of a set of different types of style sheets when they all apply to the one html element.

Style sheet Precedence

From Lowest to Highest

  1. Browser default settings
  2. User settings in browser
  3. Linked external Stylesheet
  4. Imported stylesheets
  5. Embedded stylesheets
  6. Inline Style settings
  7. HTML tag attributes

Inline Style Sheet

  • Don’t have a selector.

External Style Sheet

  • Style Sheet in an external text file
  • File must be named with the extension .css
  • External style sheet just consists of a set of Style Sheet Rules.
  • The <link> tag is unpaired tag which specifies relationships between the current document and other documents.
  • Three attributes to read in an external style sheet – rel, href and type.
&lt;html&gt;
&lt;head&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;thestyles.css&quot;
type=&quot;text/css&quot;&gt;
&lt;title&gt;External CSS Example&lt;/title&gt;
&lt;h1&gt;Testing&lt;/h1&gt;
&lt;h2&gt;I AM H2&lt;/h2&gt;
&lt;/head&gt;
&lt;/html&gt;
BODY
{
background:#ffffff;
color:#000000;
font-family:Verdana, Arial, Helvetica, san-serif;
font-size:small;
margin-top:0;
margin-left:0;
}

h1
{
color: #0000A0;
text-decoration:underline;
}
h2
{
color: red;
text-decoration:line-through;
}

Imported Style Sheets

  • Similar to external style sheets in that both varieties are held in external files.

Embedded Styles

  • In the head section of a web page.
  • Affect tags in the web page they are embedded in.
&lt;html&gt;
&lt;head&gt;
&lt;style type=&quot;text/css&quot;&gt;
/* h1 selector is also a tag */
h1{color:#0000FF;
background-color: FFFFFF;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;
The heading gets its properties from an embedded stylesheet&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;

Style Sheet Selector

  • Selector – tells the browser where a CSS rule is to be applied and can be user defined (class and id selectors) or based on a particular tag.
  • Tag – Defines how the affected element of all instances of a particular tag display.
  • ID – A style is given an identifier and tags are given the same identifier by using the id attribute.
  • Class – Tags can use this style by using the class attribute.
  • Inline – A tag has a style defined specifically for itself using the style attribute.
&lt;html&gt;
&lt;head&gt;
&lt;style type=&quot;text/css&quot;&gt;

p{color:red;}
#second {color:blue;}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;Here is a paragraph&lt;/p&gt;
&lt;p id=&quot;second&quot;&gt;Here is another one&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;

The z-index

  • Alter the precedence of images, such as when two or more slides overlap, we can alter which one appears on top.

Benefits of CSS

  • Separate structure and appearance to produce cleaner HTML which is only concerned with structure.
  • Reduce bandwidth requirements.
  • Reduce development time.
  • Reduce updating and maintenance time
  • Follow W3C recommendations.
  • Facilitate the upgrading to more recent standards (XML, XHTML).