<?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
<?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>";
}
?>
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);
?>
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.
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.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>
<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>
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();
?>
Variables declared in a function remains only in the function. You can however use global variables should you wish to use variables within a function.
<?php
$value = 100;
function currentmoney() {
global $value;
echo " I currently have RM $value <br>";
}
currentmoney();
?>
ARRAYS
Creating arrays
In order to create an array, you would need to you the array function:
In this workshop, we will look into Flow Control in PHP
If Statements
<?php
$subject = "ITC382" ;
If ($subject == "ITC382") {
Echo " I am in ITC382 class";
}
?>
If .. else statements
<?php
$subject = "ITC254" ;
If ($subject == "ITC382") {
Echo " I am in ITC382 class";}
Else {echo " I am in the wrong class";) }
?>
If..elseif ..else statements
<?php
$subject = "ITC254" ;
If ($subject == "ITC382") {
Echo " I am in ITC382 class";}
Else if ($subject == "ITC254") {
echo "I am in ITC254 class ";}
else { echo " I'm not too sure which class I should be in. Maybe I should be in $subject"; }
?>
Switch statements
Switch is commonly used to execute different codes based on each expression used.
<?php
$subject = "ITC382";
switch ($subject) {
case "ITC254":
echo "I am in ITC254 class";
break;
case "ITC382":
echo "I am in ITC382 class";
break;
default:
print "I must have gotten lost again, I am suppose to be in $subject";
break;
}
?>
While statements
A continuos loop until a condition is reached.
<?php
$count = 1;
while ($count < 10) {
echo " This is line $count", "<br>";
$count++; // Increment count by 1
}
?>
Do..While statements
It is similar to the Do statement except that termination is at the end of the code.
<?php
$count = 0;
do {
echo " This is line $count", "<br>";
$count++; // Increment count by 1
} while ($count < 10);
?>
For statements
For statements are also similar to while statements, it is a more structured way to write looping statements with the initialization, testing and modification expression nested within the command.
<?php
for ($count =1; $count <10; $count++) {
echo "This is line $count", "<br>";
}
?>
As we have chosen to solve Case A in Exercise 5, we will now cover some PHP exercises to provide practice in development skills that are needed in developing eSystems.
In this second workshop we will begin on practicing simple codes for PHP development.
W will start with all the basics first, here we go!
Remember that all PHP files will have .php extension
Commenting codes in PHP works similarly to other programming languages, here's an example:
# This starts the comments
// This also starts the comments
Multi line comments are also possible like this:
/*
This is the start of the comment.
Anything within this lines will not
Be interpreted by the PHP engine
*/
Also remember that inside everly line of a PHP code, we need to include a terminator with a semicolon ;
example:
<?php
echo "This is my first PHP program " ;
?>
Variables
In PHP variables starts with $ sign followed by the name.
$variable1
<?php
// Adding two numbers together
// Assigning the variable with the value 88
$num1 = 88;
$num2 = 100;
echo "The first number is", $num1;
echo " The second number is ", $num2 ;
// Adding the two numbers
echo " The total is ", $num1 + $num2;
?>
Data Types
The six standard data types in PHP are
Integer - Whole number, 10
Double - Floating point number , 9.999
String - AlphaNumeric characters, " This is PHP "
Boolean - True/False values, TRUE
Object - Instance of class
Array - An ordered set of keys and values
Extensible Markup Language is another language used to define the syntax of markup languages.XML is a subset of SGML, and is designed to represent arbitrary structured data in a text format.SGML is the Standard Generalised Markup Language, and is an enabling technology used in publishing applications such as HTML and XML - so a working knowledge of SGML
When I put forward my opinion, I amreminded of the public speakers that get up on their soapbox each Sunday morning in Hyde Park, London to push forward their thoughts to the gathering crowd.You are my audience!Last year I started sending soapbox e-mail messages to my colleagues amusement, as well-formed XML, using my root tag element:
XML was designed to describe data with tags.It is not predefined like HTML, so you must define your own tags (as XML is self-describing).Soon I had a set of child tags for issues, facts, examples, questions and thoughts – like a developing schema or document type definition (DTD).I found that XML helped to 'see' the relationship of each element with indenting.Maybe those Hyde Park speakers practiced XML in their speeches, popular in the 19th century, without us really knowing! ☺
Instead of reading about my perspective on this subject in 12 point, Times Roman, formatted text, the notes are now presented as 'well formed'XML, using 10 point Courier New font.Note how hard it is for the eye and brain to 'parse' the raw XML content:
<?xml version="1.0" encoding='ISO-8859-1'?>
<soapbox>
<issue>
I hold the tenet that e-commerce and indeed many e-business applications, are not about commerce at all. I suggest that an e-commerce frameworkprovides a system for secure electronic transactions of a diverse nature.
</issue>
<issue>
A bank or credit card company desires a secure transaction for moving numbers and money around the Internet. Many Internet users need the same secure system for transactions without money involved at all.
<example>
a student and teacher need a secure system to exchange
assignments and marks;
</example>
<example>
a farmer and a government agency exchange water quota
figures for irrigation, also require a private, secure
transaction without money involved.
</example>
</issue>
<issue>
In this subject, you will use object modelling as a tool for designing a secure E-business application or Web object component, such as an E-catalogue, an interactive multimedia product for sale or a Shopping Cart.
</issue>
<question>
What is the significance of the thing you do?
</question>
<thought>
For each E-business component that you build and attach to Web site – the online store front, you should discuss how your component connects or relates to your UML-based model, the Online Store (Web site); its business plan for online transactions and the secure E-commerce model in the business plan.
</thought>
<issue>
Such thinking and decision-making by you, will assist the organization (and you) to see not only how all the bits fit together, but also how your work fits into a secure, portable, scalable, reusable and persistent (big picture) development plan for the E-systems infrastructure of the business entity.
</issue>
</soapbox>
XML is widely supported as an open technology for data exchange and is better designed to handle the task of managing information.XML was designed to describe data, where XML tags are not predefined in XML.You must define your own tags, hence XML is self-describing.XML uses a DTD (Document Type Definition) to formally describe the data.
XML is not a replacement for HTML.XML and HTML were designed with different goals:XML was designed to describe data and to focus on what data is; HTML was designed to display data and to focus on how data looks.HTML is about displaying information, XML is about describing information.
In the future development ofthe Web it is most likely that XML will be used to structure and describe the Web data, while HTML
will be used to format and display the same data.It is strongly believed that XML will be as important to the future of the Web as HTML has been to the foundation of the Web.XML is the future for all data transmission and data manipulation over the Web, using new protocols like SOAP.
XMLisextensibleandportable
The tags used to markup HTML documents and the structure of HTML documents is predefined.The author of HTML documents can only use tags that are defined in the HTML standard.However, XML allows you to define your own tagsand your own document structure.Since XML tags describe the data they contain, it is possible to search, sort, manipulate and render an XML document using related technologies such as XSL (Extensible Style sheet Language).
XMLparser
XML docs are highly portable – any text editor can be used.XML is both human and machine-readable.When processing XML, and XML document end with a .xml extension.An XML parser is required to check doc syntax and can support the Document Object Model (DOM) and/or the Simple API for XML (SAX).
Several parsers are available free of charge for Java, Python and other languages. DOM-based parsers build a tree structure containing the XML doc's data in memory – it allows data to be programmatically manipulated.SAX-based parsers process the docs and generate events when tags, text, comments etc. are encountered – returning data fromXML doc.XML parsers are kept at http://www.xml.com/.
XML DTD
An XML doc can reference an optional Document Type Definition (DTD) file – this defines how the XML doc is structured
XML can be used as 'well formed', using the rules of XML or 'validated' by use of a DTD.
Howcan XML be used?
XML can keep data separated fromyour HTML - HTML pages are used to display data.Data is often stored inside HTML pages.With XML this data can now be stored in a separate XML file.This way you can concentrate on using HTML for formatting and display, and be sure that changes in the underlying data will not force changes to any of your HTML code.
XML can be used to store data inside HTML documents - XML data can also be stored inside HTML pages as 'Data Islands'.You can still concentrate on using HTML for formatting and displaying the data.XML can be used as a format to exchange information.(In the real world, computer systems and databases contain data in incompatible formats.)One of the most time-consuming challenges for developers has been to exchange data between such systems
over the Internet.Converting the data to XML can greatly reduce this complexity and create data that can be read by different types of applications.XML can be used to store data in files or in databases - XML can also be used to store data in files or in databases.Applications can be written to store and retrieve information fromthe store, and generic applications can be used to display the data.
XMLschemadesignforXMLdatastructures
Several tools and XML schema languages exist.Interesting suggestions (and hints) are provided by Kennedy (2003) and Fitzgerald, M. (2002). Kennedy (2003) recommends an XML schema tool called RelaxNG, in association with RelaxNC. The key features ofRELAX NG as an XML schema development tool is that it:
·is simple
·is easy to learn
·has both an XML syntax and a compact non-XML syntax
·does not change the information set of an XML document
·supports XML namespaces
·treats attributes uniformly with elements so far as possible
·has unrestricted support for unordered content
·has unrestricted support for mixed content
·has a solid theoretical basis
·can partner with a separate data typing language (such W3C XML Schema Data types).
Kennedy (2003) also suggests using ELM tree diagrams for mapping the data and structures, in conjunction with another tool called RELAX NC - which is the human friendly formof RELAX NG.A lot of students new to XML analysis take an instance, write it up in XML and then reverse-engineer the DTD or XML schema fromthat instance.However, ELM tree diagrams have been found to be useful in faster and effective forward engineering of the XML schema.Here are some steps to follow:
2.Write the XML schema using RNC/RNG e.g. use a recipe.
3.Write up the document in XML.
Seven (7) rules for XML analysis
1.Code only the data
2.Use collection elements
3.Use groups of 'like' elements
4.Use elements to represent multi-valued data
5.Avoid mixed content
6.Use meaningful names and a standard case
7.Note that it is an iterative process.
Further tips
·With the XML tree structure, avoid 'tall trees' or 'wide hedges'
·Elements represent the data
·Attributes used for element meta-data
·Do not use attributes for content
·Mark-up documents e.g. user manual
·Mark-up documents for data transfer e.g. invoices.
The steps of:(1) mark-up XML; (2) create DTD (reverse engineer); (3) write XSL; are replaced by steps involving (1) Elm tree; (2) RelaxNC; (3) Mark-up XML; (4) write XSL.
Information integration as the problem:Is XML the solution?
While companies starting with a 'blank piece of paper' are at an advantage because they can store data in XML fromscratch (and this is of increasing importance), most existing data repositories are still managed by relational database systems.Recent XML database research has focused on extending relational database backend to handle XML data efficiently.Special algorithms need to be designed and implemented on top of existing relational databases to support efficient database queries.For large systems, the update performance of the database in addition to query execution time will be scrutinised.
Exercise8: XMLintroduction
Create an XML document for an online catalogue of cars where each car has the child elements of make, model, year, colour, engine, number_of_doors, transmission_type and accessories. The engine has child elements called number_of_cylinders and fuel_system.
SOAP and XML messaging
Simple Object Access Protocol (SOAP) is a specification developed by an industry consortium, including Microsoft and IBM - and given to apache.org as an open source standard.SOAP is implemented by many vendors including IBM, Sun and Microsoft following the same standards, which can be extended to produce specific XML messaging standards such as ebXML and Biztalk.
The specification uses XML to define the SOAP envelope as well as RPC data structures (XML schemas).This has seen SOAP and not CORBA, DCOM or RMI rise as the challenger in distributed objects architecture.While XML is seen as human readable, machine and language neutral, for some time, distributed objects systems have not been met with great enthusiasm, as they are not suited to web browser access and were difficult to implement, or in the case of CORBA binary objects, unable to penetrate firewalls.SOAP runs over HTTP or SMTP and therefore works with the firewall setup.SOAP was attractive as an open standard and has an easy to follow specification, in addition to being a lightweight (as opposed to CORBA's heavy reliance on support code).The lightweight challenger vs the heavyweight champ!
The next page explains, with the use of diagrams in Figures 5.1 & 5, how SOAP works.Vendors produce API's that handle the SOAP services for us, so we just need to learn the API to make SOAP systems work, such as Java's Web Services Development Pack, Apache SOAP 2.2 and IBM's Web Services Development Pack.
Dynamicdiscoveryofwebservices (UDDI) and describing them (WSDL)
We can define a Web Service with Web Services Definition Language (WSDL). WSDL is an XML language used to describe what SOAP systems offer and is similar in concept to writing interfaces with IDL - as the WSDL file can be stored in the registry and discovered by clients, and help with workflow automation.In Topic 6 you can learn more about RMI and CORBA, which SOAP complements and improves.WSDL is used to mark-up, advertise and automate Web services for client businesses using UDDI in Topic 7.The Universal Description Discovery Integration (UDDI) – is seen as the phonebook-style register for e- commerce, where small businesses can describe themselves, discover other businesses and look at integration of services.
It is here that we conclude Topic 5 with firmevidence of XML as a core technology for e-commerce and business applications development of Web services – storing data, and transporting data and messages to objects.Topic 5 also gives an introduction to SOAP and its practical uses in accessing resources beyond the firewall, such as Database servers, CORBA, RMI and EJB systems, as well as in exposing a web application as a stand-alone application in Web services.
SOAP was good for developing lightweight distributed component applications - by wrapping existing applications, and in automated business processes.
No wonder SOAP is the lightweight challenger for the distributed objects crown - and a good way to introduce the other main distributed objects systems – RMI and CORBA, coming up next in Topic 6.