Showing posts with label workshops. Show all posts
Showing posts with label workshops. Show all posts

Sunday, May 30, 2010

Workshop 14 : Java & CORBA


Central to a CORBA system is the Object Request Broker, which implements the request to remote objects.  Language neutrality is achieved through the use of an interface definition language (IDL) - to define the methods an object provides to the ORB.  Language mappings are used to convert the IDL file into language specific class files.  CORBA offers many sophisticated features.


Setting up a CORBA System in Java SDK 1.4
1.             Write the IDL for the objects.
2.             Use IDL compile tool to generate stubs and skeletons.
3.             Write the class that implements the interfaces of the IDL file.
4.             Write a server to connect objects to the ORB; then leave the server running.
5.             Write the client code to access the remote CORBA object via the ORB using a name server to find it.
6.             Invoke the methods using the remote object's stub.


The IDL file for HelloWorld – A Java implementation

module itc594{

struct Person{
string firstName;
string lastName;
short age;
string address;
};

struct Time{
string time;
};

struct Name{
string name;
};

typedef sequence< Person > PersonSeq;

interface HelloWorld{
string sayHello(in string inName);
Time whatsTheTime(in string country);
Person whoAreYou();
PersonSeq whoIsThere();
void addPerson(in Person aPerson);
};
};


IDL compilers are for certain languages.  For example:  Java SDK 1.4 comes with idlj.bat which creates all the CORBA support files necessary.  The IDL types are mapped to their Java equivalents.  For example:  a struct type maps to a java data structure object.  A sequence maps to an array of structs.
Creating the Object Implementation
Two approaches are suggested, either:

1.             Inheritance by extend the POA class; or
2.             Delegation using a TIE mechanism.  This is used when we want the object to extend something else to save our hierarchy tree.


Creating the CORBA server – Connecting objects to the ORB

The steps taken in getting HelloWorldServer up and running are:

Step 1)   Compile the IDL file.
C:\idlj -falltie HelloWorld.idl

Step 2)   Implement HelloWorldOperations.Java and add concrete methods.

Step 3)   Create a server class with a main method:

Make an ORB.
Create an object.
Obtain the root POA.
      Use the HelloWorldPOATie class to delegate to the object implementation.
Add it to the name service.
Keep the ORB running.

The Object Implementation code

A sample of the method implementation for the HelloWorldImpl class.  Note the use of the Person struct from the IDL.  Person becomes a basic object type after IDL compilation.



public Person whoAreYou(){
  return (Person)people.get(0);
}
public Person[] whoIsThere(){
   Person[] peopleArray = new Person[people.size()];
   for(int index =0; index<people.size(); index++){
     peopleArray[index] = (Person) people.get(index);
   }
   return peopleArray;
}
public void addPerson(Person aPerson){
   people.add(aPerson);
}
The server code

try{
  // create the ORB!
  org.omg.CORBA.ORB orb =  org.omg.CORBA.ORB.init(args, null);
  HelloWorldImpl helloWorldImpl = new HelloWorldImpl("Barry White");

  POA rootPOA = POAHelper.
    narrow(orb.resolve_initial_references("RootPOA"));
  rootPOA.the_POAManager().activate();
  HelloWorldPOATie tie = new HelloWorldPOATie(helloWorldImpl, 
  rootPOA);
  HelloWorld helloWorldRef = tie._this(orb);

  // create a nameSpace for the HelloWorld Object
  NamingContext root_context = NamingContextHelper.narrow(
  orb.resolve_initial_references("NameService"));
    
  NameComponent[] helloName1 =
    { new NameComponent( "helloWorld", "" ) };
  root_context.rebind( helloName1, helloWorldRef );
  Thread.currentThread().join();
}
catch (Exception e) {
  e.printStackTrace();
}

The Client Code
try{
  ORB orb = ORB.init(args, null);
  // Resolve the NameService to find the object
  NamingContext nameService = NamingContextHelper
    .narrow(orb.resolve_initial_references("NameService"));
 
  // resolve the Object Reference in Naming
  NameComponent[] helloName = { new NameComponent( "helloWorld", "" ) };
  HelloWorld helloWorldImpl = HelloWorldHelper.
     narrow(nameService.resolve(helloName));

  //call a method on the Stub
  System.out.println(“Say Hello Object: " + helloWorldImpl.sayHello());
}
Catch(Exception e){
  e.printStackTrace();
}

Now to get it all running…and a well-earned rest!

1.             Compile all classes!
2.             Start the Java ORB bootstrap name service
c:\start tnameserv -ORBInitialHost localhost -ORBInitialPort 900
3.             Start the server and tell it where the ORB is running
C:\start java HelloWorldServer -ORBInitialHost localhost
-ORBInitialPort 900
4.             Start the Client and tell it where the ORB is running also
C:\java HelloWorldClient -ORBInitialHost localhost
-ORBInitialPort 900


Workshop 13 : Java Remote Method Invocation


Using RMI in Java uses the Java Virtual Machine (JVM) to share objects through facilities for activating and managing object instances, and is also used with Enterprise Java Beans technology.  RMI allows classes to be downloaded from HTTP servers and can be used as an alternative to CORBA or DCOM.


 
HelloWorld in RMI
Why you would consider doing the Hello World program in RMI or CORBA is almost beyond belief, until you recognise that it is a good way for us to see a sample application.

Table 1:  The HelloWorld application as a Remote Method Invocation.

HelloWorldImpl <>
Implements the methods of the interface
Extends UnicastRemoteObject
HelloWorld <>
The interface is what the Client will see, methods.  Declared here are the ones the client sees
Extends java.rmi.Remote
java.rmi.Remote
Extending this tells the JVM that the object will be available to the RMI mechanism

UnicastRemoteObject
Provides methods that allow an object to be available to incoming calls (export)

The simple steps to exporting a remote object – the server

1.             Compile the interface with the RMIC tool.
2.             Create and bind an object to the rmiregistry


try{
  HelloWorld yoWorld = new HelloWorldImpl();
  Naming.rebind(exportName, yoWorld);
}catch(Exception e){
 e.printStackTrace();
}

3.            Create a client that looks up the object and then invokes its methods.


try {
  String exportName = "//localhost/yoHello";
  HelloWorld world = (HelloWorld) Naming.lookup(exportName);
  System.out.println(world.sayHello("bob smith"));
}catch(Exception e){
  e.printStackTrace();
}

Starting and running HelloWorld on the local machine

1.             Start the rmiregistry
C:\rmiregistry

2.             Start the server
C:\start java -Djava.security.policy=java.policy HelloWorldImpl

3.             Start the client
C:\java -Djava.security.policy=java.policy FindWorld

FindHello.java

import java.rmi.*;
import java.rmi.server.*;
import java.io.*;


public class FindHello{

public static void main(String[] args) {
System.out.println(System.getSecurityManager());
try {
String exportName = "//localhost/yoHello";
HelloWorld world = (HelloWorld)
Naming.lookup(exportName);
System.out.println(world.sayHello("bob smith"));
}catch(Exception e){
e.printStackTrace();
}
}// main
}// class

HelloWorld.java

import java.rmi.*;
public interface HelloWorld extends Remote{
public String sayHello(String yourName) throws RemoteException;

}

HelloWorldImpl.java

import java.rmi.*;
import java.rmi.server.*;
import java.util.Date;

public class HelloWorldImpl extends UnicastRemoteObject
implements HelloWorld{

public HelloWorldImpl() throws RemoteException{
super();
}

public String sayHello(String yourName){
return "Hello "+yourName+" the Time on this machine is "+
new Date().toString();
}

public static void main(String[] args) throws Exception{

System.out.println(System.getSecurityManager());


String exportName = "//localhost/yoHello";
try{
HelloWorld yoWorld = new HelloWorldImpl();
Naming.rebind(exportName, yoWorld);
}catch(Exception e){
e.printStackTrace();
}
}// main


}// class


Java.policy

grant {
    permission java.net.SocketPermission "*:1091",
        "connect,accept";
    permission java.net.SocketPermission "*:80", "connect";
};


Workshop 12 : PHP & MySQL Online Store Pt.3

In this workshop, we will further enhance the developed Online Store by adding a shopping cart functionality. To do this, we first need some new tables created in the lohky database to be able to implement the shopping cart functionality.

Mysql > use lohky 

mysql> create table store_shoppertrack(
     id int not null primary key auto_increment,
     session_id varchar (32),
     sel_item_id int,
     sel_item_qty smallint,
     sel_item_size varchar (25),
     sel_item_color varchar (25),
     date_added datetime
     );
Query OK, 0 rows affected (0.00 sec)

mysql> create table store_orders (
    -> id int not null primary key auto_increment,
    -> order_date datetime,
    -> order_name varchar (100),
    -> order_address varchar (255),
    -> order_city varchar (50),
    -> order_state char(50),
    -> order_zip varchar (10),
    -> order_tel varchar (25),
    -> order_email varchar (100),
    -> item_total float(6,2),
    -> shipping_total float (6,2),
    -> authorization varchar (50),
    -> status enum ('processed', 'pending')
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> create table store_orders_items(
    -> id int not null primary key auto_increment,
    -> order_id int,
    -> sel_item_id int,
    -> sel_item_qty smallint,
    -> sel_item_size varchar (25),
    -> sel_item_color varchar (25),
    -> sel_item_price float (6,2)
    -> )
    -> ;
Query OK, 0 rows affected (0.00 sec)


Then we move on to the PHP part of the shopping cart implementation, in which functions to manage (add/remove/view) the shopping cart is constructed:

addToCart.php:

<?php
session_start();

//connect to database
$conn = mysql_connect("localhost", "lohky", "welcome") or die(mysql_error());
mysql_select_db("lohky",$conn)  or die(mysql_error());

if ($_POST[sel_item_id] != "") {
   //validate item and get title and price
    $get_iteminfo = "select item_title from store_items where id = $_POST[sel_item_id]";
    $get_iteminfo_res = mysql_query($get_iteminfo) or die(mysql_error());

    if (mysql_num_rows($get_iteminfo_res) < 1) {
           //invalid id, send away
           header("Location: seestore.php");
           exit;
    } else {
           //get info
           $item_title =  mysql_result($get_iteminfo_res,0,'item_title');

           //add info to cart table
           $addtocart = "insert into store_shoppertrack values ('', '$PHPSESSID', '$_POST[sel_item_id]', '$_POST[sel_item_qty]', '$_POST[sel_item_size]', '$_POST[sel_item_color]', now())";
          mysql_query($addtocart);

           //redirect to showcart page
           header("Location: showcart.php");
          exit;
    }
} else {
    //send them somewhere else
    header("Location: seestore.php");
    exit;
}
?>


removeFromCart.php

<?php
session_start();
//connect to database
$conn = mysql_connect("localhost", "lohky", "welcome")  or die(mysql_error());
mysql_select_db("lohky",$conn)  or die(mysql_error());

if ($_GET[id] != "") {
    $delete_item = "delete from store_shoppertrack where id = $_GET[id] and session_id = '$PHPSESSID'";
    mysql_query($delete_item) or die(mysql_error());

    //redirect to showcart page
    header("Location: showcart.php");
    exit;

} else {
    //send them somewhere else
    header("Location: seestore.php");
    exit;
}
?>


showCart.php

<?php
session_start();

//connect to database
$conn = mysql_connect("localhost", "lohky", "welcome") or die(mysql_error());
mysql_select_db("lohky",$conn)  or die(mysql_error());

$display_block = "<h1>Your Shopping Cart</h1>";

//check for cart items based on user session id
$get_cart = "select st.id, si.item_title, si.item_price, st.sel_item_qty, st.sel_item_size, st.sel_item_color from store_shoppertrack as st  left join store_items as si on si.id = st.sel_item_id where  session_id = '$PHPSESSID'";
$get_cart_res = mysql_query($get_cart) or die(mysql_error());

if (mysql_num_rows($get_cart_res) < 1) {
    //print message
    $display_block .= "<P>You have no items in your cart.
    Please <a href=\"seestore.php\">continue to shop</a>!</p>";

} else {
    //get info and build cart display
    $display_block .= "
    <table celpadding=3 cellspacing=2 border=1 width=98%>
    <tr>
    <th>Title</th>
    <th>Size</th>
    <th>Color</th>
    <th>Price</th>
    <th>Qty</th>
    <th>Total Price</th>
    <th>Action</th>
    </tr>";

    while ($cart = mysql_fetch_array($get_cart_res)) {
           $id = $cart['id'];
           $item_title = stripslashes($cart['item_title']);
           $item_price = $cart['item_price'];
           $item_qty = $cart['item_qty'];
           $item_color = $cart['sel_item_color'];
           $item_size = $cart['sel_item_size'];
        $total_price = sprintf("%.02f", $item_price * $item_qty);

           $display_block .= "<tr>
           <td align=center>$item_title <br></td>
           <td align=center>$item_size <br></td>
           <td align=center>$item_color <br></td>
           <td align=center>\$ $item_price <br></td>
           <td align=center>$item_qty <br></td>
           <td align=center>\$ $total_price</td>
           <td align=center><a href=\"removefromcart.php?id=$id\">remove</a></td>
           </tr>";
    }

    $display_block .= "</table>";
}
?>
<HTML>
<HEAD>
<TITLE>My Store</TITLE>
</HEAD>
<BODY>
<? print $display_block; ?>
</BODY>
</HTML>

Workshop 11 : PHP & MySQL Online Store Pt.2

In this workshop, will continue our discussion on developing an Online store using the records we have created in the previous workshop with the help of some PHP programming.
First, we need to develop the PHP codes to make-up the actual Store.

<?php
//connect to database
$conn = mysql_connect("localhost", "lohky", "welcome") or die(mysql_error());
mysql_select_db("lohky",$conn)  or die(mysql_error());

$display_block = "<h1>My Categories</h1>
<P>Select a category to see its items.</p>";

//show categories first
$get_cats = "select id, cat_title, cat_desc from store_categories order by cat_title";
$get_cats_res = mysql_query($get_cats) or die(mysql_error());

if (mysql_num_rows($get_cats_res) < 1) {
   $display_block = "<P><em>Sorry, no categories to browse.</em></p>";
} else {
   while ($cats = mysql_fetch_array($get_cats_res)) {
        $cat_id  = $cats[id];
        $cat_title = strtoupper(stripslashes($cats[cat_title]));
        $cat_desc = stripslashes($cats[cat_desc]);

        $display_block .= "<p><strong><a href=\"$_SERVER[PHP_SELF]?cat_id=$cat_id\">$cat_title</a></strong><br>$cat_desc</p>";

        if ($_GET[cat_id] == $cat_id) {
           //get items
           $get_items = "select id, item_title, item_price from store_items where cat_id = $cat_id order by item_title";
           $get_items_res = mysql_query($get_items) or die(mysql_error());

           if (mysql_num_rows($get_items_res) < 1) {
                $display_block = "<P><em>Sorry, no items in this category.</em></p>";
           } else {
                $display_block .= "<ul>";

                while ($items = mysql_fetch_array($get_items_res)) {
                   $item_id  = $items[id];
                   $item_title = stripslashes($items[item_title]);
                   $item_price = $items[item_price];

                   $display_block .= "<li><a href=\"showitem.php?item_id=$item_id\">$item_title</a></strong> (\$$item_price)";
                }

                $display_block .= "</ul>";
           }
       }
   }
}
?>
<HTML>
<HEAD>
<TITLE>My Categories</TITLE>
</HEAD>
<BODY>
<? print $display_block; ?>
</BODY>
</HTML>


This code will show the products based on its categories. To view the items listed in the categories, we need these lines of codes:

<?php
//connect to database
$conn = mysql_connect("localhost", "lohky", "welcome") or die(mysql_error());
mysql_select_db("lohky",$conn)  or die(mysql_error());

$display_block = "<h1>My Store - Item Detail</h1>";

//validate item
$get_item = "select c.cat_title, si.item_title, si.item_price, si.item_desc, si.item_image from store_items as si left join store_categories as c on c.id = si.cat_id where si.id = $_GET[item_id]";
$get_item_res = mysql_query($get_item) or die (mysql_error());

if (mysql_num_rows($get_item_res) < 1) {
   //invalid item
   $display_block .= "<P><em>Invalid item selection.</em></p>";
} else {
   //valid item, get info
   $cat_title = strtoupper(stripslashes(mysql_result($get_item_res,0,'cat_title')));
   $item_title = stripslashes(mysql_result($get_item_res,0,'item_title'));
   $item_price = mysql_result($get_item_res,0,'item_price');
   $item_desc = stripslashes(mysql_result($get_item_res,0,'item_desc'));
   $item_image = mysql_result($get_item_res,0,'item_image');

   //make breadcrumb trail
   $display_block .= "<P><strong><em>You are viewing:</em><br><a href=\"seestore.php?cat_id=$cat_id\">$cat_title</a> &gt; $item_title</strong></p>
   <table cellpadding=3 cellspacing=3>
   <tr>
   <td valign=middle align=center><img src=\"$item_image\"></td>
   <td valign=middle><P><strong>Description:</strong><br>$item_desc</p>
   <P><strong>Price:</strong> \$$item_price</p>";

   //get colors
   $get_colors = "select item_color from store_item_color where item_id = $item_id order by item_color";
   $get_colors_res = mysql_query($get_colors) or die(mysql_error());

   if (mysql_num_rows($get_colors_res) > 0) {
        $display_block .= "<P><strong>Available Colors:</strong><br>";
        while ($colors = mysql_fetch_array($get_colors_res)) {
           $item_color = $colors['item_color'];
           $display_block .= "$item_color<br>";
       }
   }

   //get sizes
   $get_sizes = "select item_size from store_item_size where item_id = $item_id order by item_size";
   $get_sizes_res = mysql_query($get_sizes) or die(mysql_error());

   if (mysql_num_rows($get_sizes_res) > 0) {
       $display_block .= "<P><strong>Available Sizes:</strong><br>";

       while ($sizes = mysql_fetch_array($get_sizes_res)) {
          $item_size = $sizes['item_size'];
          $display_block .= "$item_size<br>";
       }
   }

   $display_block .= "
   </td>
   </tr>
   </table>";
}
?>
<HTML>
<HEAD>
<TITLE>My Store</TITLE>
</HEAD>
<BODY>
<? print $display_block; ?>
</BODY>
</HTML>


To view the online store, upload both .php files. name the first one seeStore.php and the second seeItems.php. After uploaded, you can visit the store by calling seeStore.php

Workshop 10 : PHP & MySQL Online Store Pt.1

In this workshop, we will discuss the steps to create a simple online store application with PHP and MySQL.

The first step is to login to the MySQL database and select/ create a database to be used. Instructions on how to do this can be found on the previous workshop. Let's use the lohky database created earlier and then create a table using t enter records to save some time. Here we go!
Mysql > use lohky 

mysql> create table store_categories (
    -> id int not null primary key auto_increment,
    -> cat_title varchar (50) unique,
    -> cat_desc text
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> create table store_items (
    -> id int not null primary key auto_increment,
    -> cat_id int not null,
    -> item_title varchar (75),
    -> item_price float (8,2),
    -> item_desc text,
    -> item_image varchar (50)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> create table store_item_size (
    -> item_id int not null,
    -> item_size varchar (25)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> create table store_item_color(
    -> item_id int not null,
    -> item_color varchar (25));
Query OK, 0 rows affected (0.00 sec)


After creating the table, we would then need to store some records inside the created tables

Insert some records onto the store_categories tables

mysql> insert into store_categories values
    -> ('1','hats','funky hats in all shapes and sizes!');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_categories values ('2', 'Shirts', 'All shapes and size
s.');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_categories values ('3', 'Books', 'Fiction and all.');
Query OK, 1 row affected (0.01 sec)


Insert some records on to the store_items table

mysql> insert into store_items values ('1', '1', 'Baseball Hat', '12.00', ' Fan
cy, low profile baseball hat.', 'baseballhat.gif');
Query OK, 1 row affected (0.07 sec)

mysql> insert into store_items values ('2', '1', 'cowboy hat', '52.00', '10 gal
lon variety', 'cowboyhat.gif');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_items values ('3', '1', 'Top Hat', '102.00', 'A classi
c', 'tophat.gif');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_items values ('4', '2', 'Short sleeve T Shirt', '12.00
', '100% cotton, pre shrunk.', 'sstshirt.gif');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_items values ('5', '2', 'Long sleeve T Shirt', '15.00
'> ', '100% cotton, pre shrunk.', 'lstshirt.gif');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_items values ('6', '2', 'Sweatshirt', '22.00
'> ', 'Ideal for chilly nights.', 'sweatshirt.gif');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_items values ('7', '3', 'Jane Self Help Book', '12.00
'> ', 'HELPING You.', 'book1.gif');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_items values ('8', '3', 'Client Server Applications',
'40.00
'> ', 'A good reference.', 'book2.gif');
Query OK, 1 row affected (0.00 sec)

mysql> insert into store_items values ('9', '3', 'Style Guru', '40.00
'> ', 'Fashionable tips.', 'book3.gif');
Query OK, 1 row affected (0.00 sec)

Insert records into the store_item_size table

mysql> Insert into store_item_size values (1, 'one size fits all');
Query OK, 1 row affected (0.00 sec)

mysql> Insert into store_item_size values (2, 'one size fits all');
Query OK, 1 row affected (0.00 sec)

mysql> Insert into store_item_size values (3, 'one size fits all');
Query OK, 1 row affected (0.00 sec)

mysql> Insert into store_item_size values (4, 'S');
Query OK, 1 row affected (0.01 sec)

mysql> Insert into store_item_size values (4, 'M');
Query OK, 1 row affected (0.00 sec)

mysql> Insert into store_item_size values (4, 'L');
Query OK, 1 row affected (0.00 sec)

mysql> Insert into store_item_size values (4, 'XL');
Query OK, 1 row affected (0.00 sec)


Insert records into the store_item_color table

mysql> Insert into store_item_color values (1, 'red');
Query OK, 1 row affected (0.00 sec)

mysql> Insert into store_item_color values (1, 'black');
Query OK, 1 row affected (0.00 sec)

mysql> Insert into store_item_color values (1, 'blue');
Query OK, 1 row affected (0.00 sec)


We now have our basic database, complete with tables and records to be used in conjuction with our PHP code which we will discuss on the next Workshop.

Tuesday, April 20, 2010

Workshop 9 PHP & MySQL

Interacting with MYSQL

1. Connecting to MYSQL
<?php 

$conn = mysql_connect("localhost", "lohky", "welcome");
echo $conn; 

?>

2. Creating a simple table

<?php 

// Opening the initial connection. Remember to change it to your own login and password
$conn = mysql_connect("localhost", "lohky", "welcome"); 

// pick the database to use 
mysql_select_db ("lohky", $conn);

// Create table 
$sql = "Create table testtable (id int not null primary key auto_increment, testfield varchar (75))"; 

// Execute the MYSQL query 
$result=mysql_query($sql, $conn); 

// Display the result indentifier 
echo $result; 

?>


Check if the table is created from MySQL manager.

3. Using the same script connect02.php. Put in an error capture and display to screen.

<?php 


// Opening the initial connection. Remember to change it to your own login and password
$conn = mysql_connect("localhost", "lohky", "welcome"); 

// pick the database to use 
mysql_select_db ("lohky", $conn);

// Create table 
$sql = "Create table testtable (id int not null primary key auto_increment, testfield varchar (75))"; 

// Execute the MYSQL query 
$result=mysql_query($sql, $conn) or die(mysql_error()); 

// Display the result indentifier 
echo $result; 

?>

4. Lets use a form now and attach a php script to insert some data into the table.
The following is a html document called insert.html. It will called the script connect04.php and insert data onto the SQL table

<HTML>
<HEAD>
<TITLE>Insert Form</TITLE>
</HEAD>
<BODY>
<FORM ACTION="connect04.php" METHOD=POST>
<P>Text to add:<br>
<input type=text name="testField" size=30>
<p><input type=submit name="submit" value="Insert Record"></p>
</FORM>
</BODY>
</HTML>

Connect04.php
<?php
// open the connection
$conn = mysql_connect("localhost", "lohky", "welcome");

// pick the database to use
mysql_select_db("UserDB",$conn);

// create the SQL statement
$sql = "INSERT INTO testtable values ('', '$_POST[testField]')";

// execute the SQL statement
if (mysql_query($sql, $conn)) {
    echo "record added!";
} else {
    echo "something went wrong";
    
}
?>



5. Retrieving some records

<?php
// open the connection
$conn = mysql_connect("localhost", "username", "password");

// pick the database to use
mysql_select_db("DB_Name",$conn);

// create the SQL statement
$sql = "SELECT * FROM testtable";

// execute the SQL statement
$result = mysql_query($sql, $conn) or die(mysql_error());

//go through each row in the result set and display data
while ($newArray = mysql_fetch_array($result)) {
    // give a name to the fields
    $id  = $newArray['id'];
    $testfield = $newArray['testfield'];
    //echo the results onscreen
    echo "The ID is $id and the text is $testfield <br>";
}
?>

Workshop 8 PHP Working with directories

Working with Files and Folders With PHP

Files

Testing files, lets test for some existence and status of a file called text1.txt

<?php 

// Checking its existence 
if (file_exists("text1.txt")) { 
    echo "The file text1.txt exists!";
} 

// checking the status of files 
if (is_readable("text1.txt")) {
    echo "The file text1.txt is readable";
}

if (is_writeable("text1.txt")) { 
    echo "The file text1.txt is writeable";
}

if (is_executable("text1.txt")) { 
    echo "The file text1.txt is exectuable";
} 
?> 

You probably only see "The file text1.txt exists". If you only see this, you will need to chmod the read,write and execute settings on that file.

Reading data from files

<?php 

$filename = "text1.txt"; 
$fp = fopen($filename, "r") or die ("Could not open $filename"); 
while (!feof($fp)) { // While not end of file 
    $data = fread($fp, 16); // Reading the file in chunkcs of 16 bytes
    echo "$data <br>";
}
?>

There are multiple ways you can read from a file includes
Fgets() : Reading line by line
Fgetc() : Reading a character


Writing to a file

<?php 

$filename = "text1.txt"; 
echo "Begin writing to file $filename <br>";
$fp = fopen($filename, "w") or die ("Could not open $filename"); // OPen for writing 
fwrite ($fp, "I'm making changes \n");
fclose($fp);
?>

If you have trouble writing to the file, it could be a permission setting. Try chmod 777 . This will give all permissions to the file only. Chmod 777 to the directory give all permissions to the directory and not advisable.

Appending to a file

<?php 

$filename = "text1.txt"; 
echo "Appending to a file $filename <br>";
$fp = fopen($filename, "a") or die ("Could not open $filename"); // OPen for writing 
fputs ($fp, "\n Another thing I want to add  \n");
fclose($fp);
?>

The file text1.txt will have a new line called Another thing I want to add.


Directories

Creating a new directory

<?php 

mkdir ("testdir", 0755);
?>

If you failed to create a directory, again it usually means you have incorrect permissions settings.


Directory listing

<?php 

$dirname = ".";
$dn = opendir($dirname) or die ("Could not open directory");

while (!(($file = readdir($dn)) === false ) ) { 
    if (is_dir("$dirname/$file")) { 
    echo "(D) "; // To signify a folder 
} 
echo "$file <br>";
}
closedir ($dn);
?>

Workshop 7 PHP Sessions

Sessions

Sessions are unique identifier of a user, which can be used to store and retrieve information attached to the user. Therefore enabling the website to know what the user have seen, browse through etc. The user would need to have cookies enabled for session to work.

1. Initializing a session

<?php
session_start();

echo "<p>Your session ID is ".session_id()."</p>";
?>

Your session id stays the same all the time.

2. Storing and accessing session variables
We'll store the variables first in a separate file

<?php
session_start();

$_SESSION[product1] = "Sonic Screwdriver";
$_SESSION[product2] = "HAL 2000";
echo "The products have been registered.";

?>


Once you have executed this script, run the next script. The above script will attached the data onto session variables.

<?php
session_start();

echo "Your chosen products are:";
echo "<ul><li>$_SESSION[product1] <li>$_SESSION[product2]\n</ul>\n";
?>


3. Destroying sessions and variables. Once executed it would remove the session and the corresponding variables

<?php 
session_start();
session_destroy(); 
unset($session[product1]); // Remove product 1 
unset($session[product2]); // Remove product 2 

// This should print nothing 
echo "Your chosen products are:";
echo "<ul><li>$_SESSION[product1] <li>$_SESSION[product2]\n</ul>\n";
?>

Workshop 6 PHP Strings, Dates and Forms

Working with Strings

1. Up to now, we've only been working on the echo statement. The printf() statement does the same thing except it can accept arguments passed onto the function.

<?php 

// This outputs the integer as a decimal number instead of part of a string 
printf("This is my number : "%d", 60) ; 

?> 


2. You can also specify the start position of your string displayed

<?php 

echo "<pre">; 
// This will leave 15 spaces before printing 
printf ("%15s\n", " Name"); 
printf ("%15s\n", " Address");
printf ("%15s\n", " Mobile Number");
printf ("%15s\n", " Email");
echo "<pre">;
?>

3. You can look up more string functions on www.php.net
• strlen() , to determine the length of a string
• strstr (), to determine the existence of a string within a string
• strpos(), to find the position of a substring


Working with Time and Date

1. PHP stores time as number of seconds that have elapsed since GMT midnight 1 January 1970. This is the time stamp

<?php 

// This is the timestamp, It is the number of seconds since Unix Epoch (Midnight GMT 1 Jan 1970) 

echo "The number of seconds that have passed since Midninght GMT 1 January 1970 is "; 
echo time(); 
echo "<br>"; 

?> 

2. With the timestamp you can convert it to date using getdate(). This is a an array that stores the vales of date.

<?php
$date_array = getdate(); // no argument passed so today's date will be used
foreach ($date_array as $key => $val) {
    echo "$key = $val<br>";
}
?>
<hr>
<?
echo "Today's date: ".$date_array['mday']."/".$date_array['mon']."/".
    $date_array['year']."<p>";
?>

Creating Forms

1. Use the following for testing.
1.1 Listing 9.1.html
<html>
<head>
<title>Listing 9.1 A simple HTML form</title>
</head>
<body>
<form action="listing9.2.php" method="POST">
<p><strong>Name:</strong><br>
<input type="text" name="user">
<p><strong>Address:</strong><br>
<textarea name="address" rows="5" cols="40"></textarea>
<P><input type="submit" value="send"></p>
</form>
</body>
</html>

1.2 Listing 9.2.php
<html>
<head>
<title>Listing 9.2 Reading input from a form </title>
</head>
<body>
<?php
echo "<p>Welcome <b>$_POST[user]</b></p>";
echo "<p>Your address is:<br><b>$_POST[address]</b></p>";
?>
</body>
</html>

There are two input boxes available from listing9.2.html called text and address. When the user submits the form it will invoke the script called listing9.2.php. The $_POST command will grab the value values corresponding to the text boxes value in listing9.1.html.


2. Getting data from a multi valued text box
2.1 Listing9.3.html
<html>
<head>
<title>Listing 9.3 An HTML form including a SELECT element</title>
</head>
<body>
<form action="listing9.4.php" method="POST">
<p><strong>Name:</strong><br>
<input type="text" name="user">

<p><strong>Address:</strong><br>
<textarea name="address" rows="5" cols="40"></textarea>

<p><strong>Select Some Products:</strong> <br>
<select name="products[]" multiple>
<option value="Sonic Screwdriver">Sonic Screwdriver</option>
<option value="Tricoder">Tricorder</option>
<option value="ORAC AI">ORAC AI</option>
<option value="HAL 2000">HAL 2000</option>
</select>

<p><input type="submit" value="send"></p>
</form>
</body>
</html>

2.2 Listing9.4.php
<html>
<head>
<title>Listing 9.4 Reading input from the form in Listing 9.3</title>
</head>
<body>
<?php
echo "<p>Welcome <b>$_POST[user]</b></p>";
echo "<p>Your address is:<br><b>$_POST[address]</b></p>";
echo "<p>Your product choices are:<br>";
if (!empty($_POST[products])) {
    echo "<ul>";
    foreach ($_POST[products] as $value) {
       echo "<li>$value";
    }
    echo "</ul>";
}
?>
</body>
</html>

3. Sending out emails

3.1 Listing9.10.html
<HTML>
<HEAD>
<TITLE>E-Mail Form</TITLE>
</HEAD>
<BODY>
<FORM action="listing9.11.php" method="POST">
<p><strong>Your Name:</strong><br> <INPUT type="text" size="25" name="name"></p>
<p><strong>Your E-Mail Address:</strong><br> <INPUT type="text" size="25" name="email"></p>
<p><strong>Message:</strong><br>
<textarea name="message" cols=30 rows=5></textarea></p>
<p><INPUT type="submit" value="send"></p>
</FORM>
</BODY>
</HTML>

3.2 Listing.9.11.php
<html>
<head>
<title>Listing 9.11 Sending mail from the form in Listing 9.10</title>
</head>
<body>
<?php
echo "<p>Thank you, <b>$_POST[name]</b>, for your message!</p>";
echo "<p>Your e-mail address is: <b>$_POST[email]</b></p>";
echo "<p>Your message was:<br>";
echo "$_POST[message] </p>";

//start building the mail string
$msg = "Name:     $_POST[name]\n";
$msg .= "E-Mail:   $_POST[email]\n";
$msg .= "Message:  $_POST[message]\n";

//set up the mail
$recipient = "youremail@youraddress"; //Remember to change the email to your address 
$subject = "ITC594 Workshop Testing";
$mailheaders = "From: My Web Site <http://192.168.6.200 \n";
$mailheaders .= "Reply-To: $_POST[email]";

//send the mail
mail($recipient, $subject, $msg, $mailheaders);
?>
</body>
</html>


Workshop 5 Working with Objects in PHP

OBJECTS

An object is typically a sort of container that consists of
variables
functions
etc
An object in php is similar to a class object in JAVA

<?php

class lecturers {
    var $name = "Yann";
    var $subjectcode  = "ITC382" ;
    var $subjectname = "Client Server Applications";
    }

$mylecturer = new lecturers();
echo "My name is ".$mylecturer -> name. " and I teach " .$mylecturer -> subjectcode." " .$mylecturer -> subjectname;

?>

You can also change the properties of an object in the code as illustrated.

<?php

class lecturers {
    var $name = "Yann";
    var $subjectcode  = "ITC382" ;
    var $subjectname = "Client Server Applications";
    }

$mylecturer = new lecturers();
echo "My name is ".$mylecturer -> name. " and I teach " .$mylecturer -> subjectcode." " .$mylecturer -> subjectname;


// changing the object properties
echo "<br> This is to relfect the changes in object properties <br>";
$mylecturer -> name = "Sam";
$mylecturer -> subjectcode = "ITC211";
$mylecturer -> subjectname = "Multimedia Systems";

echo "My name is ".$mylecturer -> name. " and I teach " .$mylecturer -> subjectcode." " .$mylecturer -> subjectname;

?>

You can also add methods into your class objects as illustrated.

<?php

class displayname {
    function name() {
            echo "My name is Yann " ;
            } 
       }

$name = new displayname();
$name  -> name();
?>