ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
L
eCommerce Course:PHP, PostgreSQL & XML
Javier VazquezUtrecht University
e-mail: [email protected]
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LContents
• Architecture of the combined catalog system
• PHP
• PHP and PostgreSQL database
• PHP for XML parsing
• Useful links
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
L
Architecture of the combined catalog system
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LArchitecture of the combined catalog system (1/2)Entities and integration problem
dbdb--11
RETAILER 1RETAILER 1
dbdb--22
RETAILER 2RETAILER 2
dbdb--33
VENDOR 1VENDOR 1
dbdb--44
VENDOR 2VENDOR 2
STORE WEBSITESTORE WEBSITE
??
ProductProductSupplierSupplier
ProductsProducts
GoodsGoods--forfor--SaleSale
CategoryCategoryProductProduct
HTMLHTML
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LArchitecture of the combined catalog system (2/2)Our solution
dbdb--11
RETAILER 1RETAILER 1
XMLXML
dbdb--22
RETAILER 2RETAILER 2
dbdb--33
VENDOR 1VENDOR 1
dbdb--44
VENDOR 2VENDOR 2
STORE WEBSITESTORE WEBSITE
HTMLHTML
XMLXML
XMLXML
XMLXML
XMLXML
XSLTXSLT
PHPPHP
XSLTXSLT
XSLTXSLT
XSLT
XSLT
XSLTXSLT
• What is PHP?
• DB (SQL) XML?
• XML HTML?
PHPPHP
PHPPHP
PHPPHP
•• What is PHP?
• DB (SQL) XML?
• XML HTML?
PHPPHP
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
L
PHP
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (1/7)What is PHP?
• PHP is a server-side scripting language embedded in HTML– Allows dynamic HTML pages
• Page content may change for each visitor and/or for each access
– The scripts are executed in the server
– The client sees only the final HTML page
• Depends not in client-side browser capabilities (cookies, JavaScript) or plug-ins (java applets).
• Scripts cannot be disconnected by the client.
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (2/7)An example
<HTML> <head><?php
error_reporting(E_ALL); // Paranoid interpreter
define("pi",3.141159);$name = 10;$name = "Javier";echo "<title>Example for $name</title>";
?></head><body><?php
echo "Howdy $name, I'm a PHP script!";
?> Generated in html.</body>
</HTML>
(Adapted from (Adapted from Jurrian Hage’sJurrian Hage’s PHP slides PHP slides [2]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//phpphp--1.1.phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (2/7)An example
<HTML> <head><?php
error_reporting(E_ALL); // Paranoid interpreter
define("pi",3.141159);$name = 10;$name = "Javier";echo "<title>Example for $name</title>";
?></head><body><?php
echo "Howdy $name, I'm a PHP script!";
?> Generated in html.</body>
</HTML>
(Adapted from (Adapted from Jurrian Hage’sJurrian Hage’s PHP slides PHP slides [2]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//phpphp--1.1.phpphp
<HTML> <head><title>Example for Javier</title>;
</head><body>Howdy Javier, I'm a PHP script! Generated in html.
</body></HTML>
<HTML> <head><title>Example for Javier</title>;
</head><body>Howdy Javier, I'm a PHP script! Generated in html.
</body></HTML>
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (3/7)Syntaxis
• Syntax is an adaptation of C– ; {} // /* */– variable names with $– no type definition– for , while, if …else,
do…while, switch– foreach for associative arrays– assignation with =,
comparison with = =– strings with ' ' or " "– whitespaces and breaklines are
ignored by browser• Use \n or \n\r
<HTML> <head><?phperror_reporting(E_ALL); echo "<title>Example of PHP</title>";
?></head><body><?php$name = 10;$name = "Javier";$times = 5;for ($i = 0; $i < $times; $i++)for ($i = 0; $i < $times; $i++){echo "Howdy $name,
I'm a PHP script!\n";if($i = ($times if($i = ($times -- 2))2))echo "so.. Don’t forget!\n";
} ?> Generated in html.
</body></HTML>
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (3/7)Syntaxis
• Syntax is an adaptation of C– ; {} // /* */– variable names with $– no type definition– for , while, if …else,
do…while, switch– foreach for associative
arrays– assignation with =,
comparison with = =– strings with ' ' or " "– whitespaces and breaklines
are ignored by browser• Use \n or \n\r
<HTML> <head><?phperror_reporting(E_ALL); echo "<title>Example of PHP</title>";
?></head><body><?php$name = 10;$name = "Javier";$times = 5;for ($i = 0; $i < $times; $i++){echo "Howdy $name,
I'm a PHP script!\n";if($i = ($times - 2))echo "so.. Don’t forget!\n";
} ?> Generated in html.
</body></HTML>
<HTML> <head><title>Example for Javier</title>;
</head><body>Howdy Javier, I'm a PHP script!Howdy Javier, I'm a PHP script!Howdy Javier, I'm a PHP script!Howdy Javier, I'm a PHP script!so... Don’t forget!Howdy Javier, I'm a PHP script! Generated in html.
</body></HTML>
<HTML> <head><title>Example for Javier</title>;
</head><body>Howdy Javier, I'm a PHP script!Howdy Javier, I'm a PHP script!Howdy Javier, I'm a PHP script!Howdy Javier, I'm a PHP script!so... Don’t forget!Howdy Javier, I'm a PHP script! Generated in html.
</body></HTML>
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (4/7)Data types
• Booleans– true, false– FALSE 0 0.0 "" NULL
• Integers and floats– 5, 7, 39.5– + - * / += -= ++ --
• Strings– ’hello’, "hello"– Single ‘ gives literal strings (no
interpretation of what is inside)• ’Hello $name /n/t’
– To print a string:echo "hello";print("hello");
• Associative arrays– Map keys to values– Keys can be numbers or strings– They are not ordered by key
– array_keys($Arr) gives (1,2,”Scary”,0)
– array_value($Arr) gives (“Dog”,”Cat”,”Bat”,”Rat”)
– There are some sort functions:sort, asort, ksort,…
– To print an array value: print_r($Arr)
$Arr = array (1 => "Dog", "Cat", "Scary" => "Bat");
$Arr[0] = "Rat";
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (5/7)Data types
class Cart {var $items; //items in the shopping cart
function add_item ($function add_item ($artnumartnum,$num),$num){
$this$this-->items[$>items[$artnrartnr] += $num;] += $num;}
function remove_item ($artnum,$num){if ($this->items[$artnr] > $num){$this->items[$artnr] -=;return true;
}else return false;
}}
$cart = new Cart;$cart = new Cart;
$cart$cart-->add_item("10",1);>add_item("10",1);
• Objects and classes
– Similar to C++ but simplified
– Objects are dynamic• methods and attributes can
be added at runtime
– $this refers to the object itself
– -> to refer to the object’s attributes and methods
• right: $object->field
• wrong: $object->$field
– :: to refer to static methods• Class::method()
(Adapted from (Adapted from Jurrian Hage’sJurrian Hage’s PHP slides PHP slides [2]))
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (6/7)Global arrays accessible from PHP. Use of foreach
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>Global Array</title><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></head><body><h1>Global Array</h1><p><?php
foreachforeach($GLOBALS as $key=>$value)($GLOBALS as $key=>$value)print $key$key . " = " . $value$value . "<br>";
?></p></body></html>
(Adapted from the Juicy Studio PHP tutorial (Adapted from the Juicy Studio PHP tutorial [4]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//foreachforeach..phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (6/7)Global arrays accessible from PHP. Use of foreach
(Adapted from the Juicy Studio PHP tutorial (Adapted from the Juicy Studio PHP tutorial [4]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//foreachforeach..phpphp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>Global Array</title><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></head><body><h1>Global Array</h1><p><?php
foreachforeach($GLOBALS as $key=>$value)($GLOBALS as $key=>$value)print $key$key . " = " . $value$value . "<br>";
?></p></body></html>
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (7/7)Form handling
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>User Details</title><meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1"></head><body><h1>User Details</h1><form id="userDetails" name="userDetails"
method="post" action="welcome.welcome.phpphp"><p>
Enter your Name: <br><input type="text" size="40" value="" name="namename"><br>Enter your Age: <br><input type="text" size="5" value="" name="ageage"><br><input type="submit" value="Enter" name="welcome">
</p></form></body></html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>Welcome</title><meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1"></head><body><p><?php
print "Welcome " . $_POST["name"]$_POST["name"] . "<br>";print "I see you are " . $_POST["age"]$_POST["age"] . " years old! <br>";
?></p></body></html>
(Adapted from the Juicy Studio PHP tutorial (Adapted from the Juicy Studio PHP tutorial [4]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//simpleFormsimpleForm.html.html
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP (7/7)Form handling
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>User Details</title><meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1"></head><body><h1>User Details</h1><form id="userDetails" name="userDetails"
method="post" action="welcome.welcome.phpphp"><p>
Enter your Name: <br><input type="text" size="40" value="" name="namename"><br>Enter your Age: <br><input type="text" size="5" value="" name="ageage"><br><input type="submit" value="Enter" name="welcome">
</p></form></body></html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>Welcome</title><meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1"></head><body><p><?php
print "Welcome " . $_POST["name"]$_POST["name"] . "<br>";print "I see you are " . $_POST["age"]$_POST["age"] . " years old! <br>";
?></p></body></html>
(Adapted from the Juicy Studio PHP tutorial (Adapted from the Juicy Studio PHP tutorial [4]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//simpleFormsimpleForm.html.html
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
L
PHP and PostgreSQL database
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (1/6)Introduction
• PostgreSQL is an open source DBMS with most of the features present in large commercial DBMS’s– Transactions, subselects, triggers, foreign key referencial integrity– Multi-user, views, multi-version concurrency control
• MySQL is another open source DBMS– faster for simple queries– lacks almost all the characteristics above.
• PostgreSQL is highly reliable, and used by companies.
• PHP has library functions to connect easily to PostgreSQL (and also to MySQL).
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (2/6)Connecting, disconnecting and error handling
<?php$dbcomm = @pg_connect@pg_connect("host=tricolor.students.cs.uu.nl
port=5432 dbname=XXXXX user=YYYYYY password=WWWWWW")or die("Could not connect to db");
echo "Connected succesfully";pg_close($dbcomm);
?>
(Adapted from PHP manual(Adapted from PHP manual [3]))Test it: http://www.students.Test it: http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//DBtestDBtest..phpphp
<?php$dbcomm = pg_connectpg_connect("host=tricolor.students.cs.uu.nl
port=5432 dbname=XXXXX user=YYYYYY password=WWWWWW")or dieor die("Could not connect to db");
echo "Connected succesfully";pg_close($dbcomm);
?>
<?php$$dbcommdbcomm = pg_connect("host=tricolor.students.= pg_connect("host=tricolor.students.cscs..uuuu..nlnl
port=5432port=5432 dbnamedbname=XXXXX user=YYYYYY password=WWWWWW")=XXXXX user=YYYYYY password=WWWWWW")
if(!$dbconn){ echo "Could not connect to db. \n";exit;
}
echo "Connected succesfully";pg_close($pg_close($dbcommdbcomm));
?>
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (2/6)Connecting, disconnecting and error handling
<?php$dbcomm = @pg_connect@pg_connect("host=tricolor.students.cs.uu.nl
port=5432 dbname=XXXXX user=YYYYYY password=WWWWWW")or die("Could not connect to db");
echo "Connected succesfully";pg_close($dbcomm);
?>
(Adapted from PHP manual(Adapted from PHP manual [3]))Test it: http://www.students.Test it: http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//DBtestDBtest..phpphp
<?php$dbcomm = pg_connectpg_connect("host=tricolor.students.cs.uu.nl
port=5432 dbname=XXXXX user=YYYYYY password=WWWWWW")or dieor die("Could not connect to db");
echo "Connected succesfully";pg_close($dbcomm);
?>
<?php$$dbcommdbcomm = pg_connect("host=tricolor.students.= pg_connect("host=tricolor.students.cscs..uuuu..nlnl
port=5432port=5432 dbnamedbname=XXXXX user=YYYYYY password=WWWWWW")=XXXXX user=YYYYYY password=WWWWWW")
if(!$dbconn){ echo "Could not connect to db. \n";exit;
}
echo "Connected succesfully";pg_close($pg_close($dbcommdbcomm));
?>
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (3/6)Displaying all rows and fields as a HTML table
<?php$dbcomm = pg_connect("host=tricolor.students.cs.uu.nl port=5432
dbname=XXXXX user=YYYYYY password=WWWWWWW")or die("Could not connect to db");
$result = pg_query($$result = pg_query($dbcommdbcomm,"SELECT * FROM test"),"SELECT * FROM test")or die("An error occured during the query");
$rows = pg_num_rows($result);pg_num_rows($result);$fields = pg_num_fields($result);pg_num_fields($result);
echo "rows = " . $rows . ", fields = " . $fields;
echo "<table border=\"1\">\n";
for($row_num = 0; $row_num < $rows; $row_num++){
$arr = pg_fetch_array($result);pg_fetch_array($result);
echo "<tr>\n";
for($field_num = 0; $field_num < $fields; $field_num++){
echo "<td>" . $$arrarr[$field_num][$field_num] . "</td>\n";}
echo "</tr>\n";}
echo "</table>\n";
pg_close($dbcomm);?>
Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez/DBtest2./DBtest2.phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (3/6)Displaying all rows and fields as a HTML table
<?php$dbcomm = pg_connect("host=tricolor.students.cs.uu.nl port=5432
dbname=XXXXX user=YYYYYY password=WWWWWWW")or die("Could not connect to db");
$result = pg_query($$result = pg_query($dbcommdbcomm,"SELECT * FROM test"),"SELECT * FROM test")or die("An error occured during the query");
$rows = pg_num_rows($result);pg_num_rows($result);$fields = pg_num_fields($result);pg_num_fields($result);
echo "rows = " . $rows . ", fields = " . $fields;
echo "<table border=\"1\">\n";
for($row_num = 0; $row_num < $rows; $row_num++){
$arr = pg_fetch_array($result);pg_fetch_array($result);
echo "<tr>\n";
for($field_num = 0; $field_num < $fields; $field_num++){
echo "<td>" . $$arrarr[$field_num][$field_num] . "</td>\n";}
echo "</tr>\n";}
echo "</table>\n";
pg_close($dbcomm);?>
Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez/DBtest2./DBtest2.phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (4/6)Displaying all rows and fields as a HTML table
<?php$dbcomm = pg_connect("host=tricolor.students.cs.uu.nl port=5432
dbname=XXXXX user=YYYYYY password=WWWWWWW")or die("Could not connect to db");
$result = pg_query($dbcomm,"SELECT * FROM DemographyDemography")or die("An error occured during the query");
$rows = pg_num_rows($result);$fields = pg_num_fields($result);
echo "rows = " . $rows . ", fields = " . $fields;
echo "<table border=\"1\">\n";for($row_num = 0; $row_num < $rows; $row_num++){
$arr = pg_fetch_array($result);
echo "<tr>\n";
for($field_num = 0; $field_num < $fields; $field_num++){
echo "<td>" . $arr[$field_num] . "</td>\n";}
echo "</tr>\n";}
echo "</table>\n";
pg_close($dbcomm);?>
Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez/DBtest2b./DBtest2b.phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (4/6)Displaying all rows and fields as a HTML table
<?php$dbcomm = pg_connect("host=tricolor.students.cs.uu.nl port=5432
dbname=XXXXX user=YYYYYY password=WWWWWWW")or die("Could not connect to db");
$result = pg_query($dbcomm,"SELECT * FROM DemographyDemography")or die("An error occured during the query");
$rows = pg_num_rows($result);$fields = pg_num_fields($result);
echo "rows = " . $rows . ", fields = " . $fields;
echo "<table border=\"1\">\n";for($row_num = 0; $row_num < $rows; $row_num++){
$arr = pg_fetch_array($result);
echo "<tr>\n";
for($field_num = 0; $field_num < $fields; $field_num++){
echo "<td>" . $arr[$field_num] . "</td>\n";}
echo "</tr>\n";}
echo "</table>\n";
pg_close($dbcomm);?>
Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez/DBtest2b./DBtest2b.phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (5/6)Accessing to row fields by name
<?php$dbcomm = pg_connect("host=tricolor.students.cs.uu.nl port=5432
dbname=XXXX user=YYYY password=WWWWWW")or die("Could not connect to db");
$result = pg_query($dbcomm,"SELECT * FROM test")or die("An error occured during the query");
$rows = pg_num_rows($result);$fields = pg_num_fields($result);
echo "rows = " . $rows . ", fields = " . $fields;
echo "<table border=\"1\">\n";echo "<echo "<trtr> <> <thth>id</>id</thth> <> <thth>name</>name</thth> </> </trtr>";>";
for($row_num = 0; $row_num < $rows; $row_num++){
$arr = pg_fetch_array($result);
echo "<tr>\n";
echo "<td>" . $$arrarr["id"]["id"] . "</td>\n";echo "<td>" . $$arrarr["name"]["name"] . "</td>\n";
echo "</tr>\n";}
echo "</table>\n";
pg_close($dbcomm);?>
Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez/DBtest3./DBtest3.phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (5/6)Accessing to row fields by name
<?php$dbcomm = pg_connect("host=tricolor.students.cs.uu.nl port=5432
dbname=XXXX user=YYYY password=WWWWWW")or die("Could not connect to db");
$result = pg_query($dbcomm,"SELECT * FROM test")or die("An error occured during the query");
$rows = pg_num_rows($result);$fields = pg_num_fields($result);
echo "rows = " . $rows . ", fields = " . $fields;
echo "<table border=\"1\">\n";echo "<echo "<trtr> <> <thth>id</>id</thth> <> <thth>name</>name</thth> </> </trtr>";>";
for($row_num = 0; $row_num < $rows; $row_num++){
$arr = pg_fetch_array($result);
echo "<tr>\n";
echo "<td>" . $$arrarr["id"]["id"] . "</td>\n";echo "<td>" . $$arrarr["name"]["name"] . "</td>\n";
echo "</tr>\n";}
echo "</table>\n";
pg_close($dbcomm);?>
Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez/DBtest3./DBtest3.phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP and PostgreSQL database (6/6)Adapting this to the assignment
dbdb--11
RETAILER 1RETAILER 1• Adapting the last example to
create a XML structure instead of a HTML table is straight-forward
– Place XML element tags instead of the HTML tabletags
• In the assignment you have to adapt it for each of the DB’s that you want to connect
XMLXML
Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez/DBtest3./DBtest3.phpphp
dbdb--22
RETAILER 2RETAILER 2
dbdb--33
VENDOR 1VENDOR 1
dbdb--44
VENDOR 2VENDOR 2
XMLXML
XMLXML
XMLXML
PHPPHP
XSLT
XSLT
XSLT
XSLT
PHPPHPXML
PHPPHP
PHPPHP
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
L
PHP for XML parsing
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (1/9)Introduction
• PHP provides some library functions for XML parsing.
• This library functions are not part of the basic PHP library…
• … but an extension that is usually installed in most webservers
• The library allows to parse, but not validatebut not validate, XML documents.
• It supports three source character encodings: – US-ASCII, ISO-8859-1 and UTF-8. – UTF-16 is not supported.
• It is based on the creation of a parametrized parser, that the programmer can adapt within some limits.
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (2/9)catalog.xml
<?xml version="1.0"?><catalog>
<product> <name> Textil </name><manufacturer>
<mname> Bazar </mname><price> 19.99 </price><address> India </address>
</manufacturer></product><product>
<name> Red glass dragon </name><manufacturer>
<mname> Mirota </mname><price> 22.99 </price><address> Indonesia </address>
</manufacturer></product>
</catalog>
• As an example, we will use a simplified XML catalog– Products and
manufacturers.– All tags are different
(Adapted from example in eCommerce XML slides)(Adapted from example in eCommerce XML slides)
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (3/9)Setting the XML parser
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<title>XML with PHP</title><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head><body><?php
echo "<table border=\"1\">";//Initialize Parser$parser=xml_parser_create();$parser=xml_parser_create();//Specify Handlers to start and ending tagxml_set_element_handler($parser, "start_tag", "end_tag");xml_set_element_handler($parser, "start_tag", "end_tag");//Data Handlerxml_set_character_data_handler($parser, "content_handler");xml_set_character_data_handler($parser, "content_handler");//Open the Data File $$fpfp==fopenfopen("catalog.xml", "r") ;("catalog.xml", "r") ;//read Datawhile ($data=freadfread($($fpfp, 4096), 4096)){
xml_parse($parser, $data,xml_parse($parser, $data,feoffeof($($fpfp)) or )) or diedie (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),xml_get_current_line_number($parser)));
}xml_parser_free($parser)xml_parser_free($parser);echo "</table>";
function start_tag($parser, $tag_name, $attrs){
switch($tag_name){case "PRODUCT":
echo "<tr>";break;
case "NAME":echo "<td>";break;
case "MNAME":echo "<td>";break;
case "PRICE":echo "<td>";break;
case "ADDRESS":echo "<td>";
}}
function end_tag($parser, $tag_name){
switch($tag_name){case "PRODUCT":
echo "</tr>";break;
case "NAME":echo "</td>";break;
case "MNAME":echo "</td>";break;
case "PRICE":echo "</td>";break;
case "ADDRESS":echo "</td>";
}}
function content_handler($parser,$data){
echo $data;}
?></body></html>
(Adapted from PHP manual (Adapted from PHP manual [3]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez/xml2html./xml2html.phpphp
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (4/9)
• Problems– It doesn’t use DTD’s– It transforms the XML elements one by one, and in the order that
they appear• Highly dependent on the order of the tags
– If there is more than one tag with the same name• E.g., <product> <name> … and <manufacturer> <name>…
• Solution– Store the XML nodes in an intermediate structure, in memory
• PHP arrays.– Transform the PHP arrays in something else easier to handle
• PHP classes and objects.
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (5/9)moldb.xml
• We will start with a simplier XML file– A molecule database
• We parse the XML file, storing the contents in PHP associative arrays
• Then we transform the arrays in objects, for an easier use.
<?xml version="1.0"?><moldb>
<molecule><name>Alanine</name><symbol>ala</symbol><code>A</code><type>hydrophobic</type>
</molecule>
<molecule><name>Lysine</name><symbol>lys</symbol><code>K</code><type>charged</type>
</molecule>
</moldb>
(Adapted from PHP manual (Adapted from PHP manual [3]))
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (6/9)Improving the XML parser
(Adapted from PHP manual (Adapted from PHP manual [3]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//parseMolDBparseMolDB..phpphp
<?php
classclass AminoAcidAminoAcid {{varvar $name; //$name; // aaaa namenamevarvar $symbol; // three letter symbol$symbol; // three letter symbolvarvar $code; // one letter code$code; // one letter codevarvar $type; // hydrophobic, charged or neutral$type; // hydrophobic, charged or neutral
functionfunction AminoAcidAminoAcid ($($aaaa)){{
foreachforeach ($($aaaa as $k=>$v)as $k=>$v)$this$this-->$k = $>$k = $aaaa[$k];[$k];
}}}}
function readDatabase($filename){
// read the XML database of aminoacids$data = implode("", file($filename));$parser = xml_parser_create();xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);xml_parse_into_struct($parser, $data, $values, $tags);xml_parser_free($parser);echo"<pre>"; //HTML pre-formatted text tagecho "\n\n***************************** Original XML file
**************************\n";echo " ------- (Use the 'View Page Source' option of
your browser) -------\n";print($data);echo "\n\n***************************** PHP values array
**************************\n";print_r($values);echo "\n\n***************************** PHP index array
**************************\n";print_r($tags);echo"</pre>";
// loop through the structuresforeach ($tags as $key=>$val) {
if ($key == "molecule") {$molranges = $val;// each contiguous pair of array entries are the// lower and upper range for each molecule definitionfor ($i=0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;$len = $molranges[$i + 1] - $offset;$tdb[] = parseMol(array_slice($values, $offset,
$len));}
} else {continue;
}}return $tdb;
}
function parseMol($mvalues){
for ($i=0; $i < count($mvalues); $i++) {$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}return newreturn new AminoAcidAminoAcid($mol)($mol);
}
$db = readDatabase("moldb.xml");echo"<pre>"; //HTML pre-formatted text tagecho "\n\n***************************** Final data structure **************************\n";print_r($db);echo"</pre>";?>
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (6/9)Improving the XML parser
************ PHP values array **************Array(
[0] => Array(
[tag] => moldb[type] => open[level] => 1
)
[1] => Array(
[tag] => molecule[type] => open[level] => 2
)
[2] => Array(
[tag] => name[type] => complete[level] => 3[value] => Alanine
)
[3] => Array(
[tag] => symbol[type] => complete[level] => 3[value] => ala
)
[4] => Array(
[tag] => code[type] => complete[level] => 3[value] => A
)
[5] => Array(
[tag] => type[type] => complete[level] => 3[value] => hydrophobic
)
[6] => Array(
[tag] => molecule[type] => close[level] => 2
)
*********** PHP index array *******Array(
[moldb] => Array(
[0] => 0[1] => 13
)
[molecule] => Array(
[0] => 1[1] => 6[2] => 7[3] => 12
)
[name] => Array(
[0] => 2[1] => 8
)
[symbol] => Array(
[0] => 3[1] => 9
)
[code] => Array(
[0] => 4[1] => 10
)
[type] => Array(
[0] => 5[1] => 11
)
)
********* Final data structure ********Array(
[0] => aminoacid Object(
[name] => Alanine[symbol] => ala[code] => A[type] => hydrophobic
)
[1] => aminoacid Object(
[name] => Lysine[symbol] => lys[code] => K[type] => charged
)
)
[7] => Array(
[tag] => molecule[type] => open[level] => 2
)
[8] => Array(
[tag] => name[type] => complete[level] => 3[value] => Lysine
)
[9] => Array(
[tag] => symbol[type] => complete[level] => 3[value] => lys
)
[10] => Array(
[tag] => code[type] => complete[level] => 3[value] => K
)
[11] => Array(
[tag] => type[type] => complete[level] => 3[value] => charged
)
[12] => Array(
[tag] => molecule[type] => close[level] => 2
)
[13] => Array(
[tag] => moldb[type] => close[level] => 1
)
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (7/9)Adapting the parser to our catalogAdapting the parser to our catalog
(Adapted from PHP manual (Adapted from PHP manual [3]))Test it: Test it: http://www.students.http://www.students.cscs..uuuu..nlnl/~/~jvazquezjvazquez//parseCatalogparseCatalog..phpphp
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"></head><body><?php
class Product {class Product {varvar $name; // product name$name; // product namevarvar $$mnamemname; // manufacturer name; // manufacturer namevarvar $price; //$price; //varvar $address; // $address; //
function Product ($function Product ($aaaa)){{
foreachforeach ($($aaaa as $k=>$v)as $k=>$v){{if ($k!="manufacturer")if ($k!="manufacturer"){{$this$this-->$k = $>$k = $aaaa[$k];[$k];
}}} }
}}
}
function readDatabase($filename){
// read the XML database of aminoacids$data = implode("", file($filename));$parser = xml_parser_create();xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);xml_parse_into_struct($parser, $data, $values, $tags);xml_parser_free($parser);echo"<pre>"; //HTML pre-formatted text tagecho "\n\n***************************** Original XML file
**************************\n";echo " ------- (Use the 'View Page Source' option
of your browser) -------\n";print($data);echo "\n\n***************************** PHP values array
**************************\n";print_r($values);echo "\n\n***************************** PHP index array
**************************\n";print_r($tags);echo"</pre>";
// loop through the structuresforeach ($tags as $key=>$val) {
if ($key == "product""product") {$molranges = $val;// each contiguous pair of array entries are the// lower and upper range for each product definitionfor ($i=0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;$len = $molranges[$i + 1] - $offset;$tdb[] = parseMol(array_slice($values, $offset, $len));
}} else {
continue;}
}return $tdb;
}
function parseMol($mvalues){
for ($i=0; $i < count($mvalues); $i++) {$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}return new Product($mol);return new Product($mol);
}
functionfunction printAsTableprintAsTable($($aaaa)){{
echo "<table border=echo "<table border=\\"1"1\\">";">";
foreachforeach ($($aaaa as $k=>$v)as $k=>$v){{
print "<print "<trtr><td>" . $v><td>" . $v-->name . "</td><td>" . >name . "</td><td>" . $v$v-->>mnamemname . "</td><td>" . $v. "</td><td>" . $v-->price . "</td><td>" .>price . "</td><td>" .$v$v-->address . "</td></>address . "</td></trtr>";>";
} } echo"</table>"; echo"</table>";
}}
$db = readDatabase("catalog.xmlcatalog.xml");echo"<pre>"; //HTML pre-formatted text tagecho "\n\n***************************** Final data structure **************************\n";print_r($db);echo"</pre>";printAsTableprintAsTable($db);($db);
?> </body></html>
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (7/9) Adapting the parser to our catalogAdapting the parser to our catalog
***** PHP values array *********Array(
[0] => Array(
[tag] => catalog[type] => open[level] => 1
)
[1] => Array(
[tag] => product[type] => open[level] => 2
)
[2] => Array(
[tag] => name[type] => complete[level] => 3[value] => Textil
)
[3] => Array(
[tag] => manufacturer[type] => open[level] => 3
)
[4] => Array(
[tag] => mname[type] => complete[level] => 4[value] => Bazar
)
[5] => Array(
[tag] => price[type] => complete[level] => 4[value] => 19.99
)
[6] => Array(
[tag] => address[type] => complete[level] => 4[value] => India
)
[7] => Array(
[tag] => manufacturer[type] => close[level] => 3
)
[8] => Array(
[tag] => product[type] => close[level] => 2
)
[9] => Array(
[tag] => product[type] => open[level] => 2
)
[10] => Array(
[tag] => name[type] => complete[level] => 3[value] => Red glass dragon
)
[11] => Array(
[tag] => manufacturer[type] => open[level] => 3
)
[12] => Array(
[tag] => mname[type] => complete[level] => 4[value] => Mirota
)
[13] => Array(
[tag] => price[type] => complete[level] => 4[value] => 22.99
)
[14] => Array(
[tag] => address[type] => complete[level] => 4[value] => Indonesia
)
[15] => Array(
[tag] => manufacturer[type] => close[level] => 3
)
[16] => Array(
[tag] => product[type] => close[level] => 2
)
[17] => Array(
[tag] => catalog[type] => close[level] => 1
)
)
******* PHP index array *******Array(
[catalog] => Array(
[0] => 0[1] => 17
)
[product] => Array(
[0] => 1[1] => 8[2] => 9[3] => 16
)
[name] => Array(
[0] => 2[1] => 10
)
[manufacturer] => Array(
[0] => 3[1] => 7[2] => 11[3] => 15
)
[mname] => Array(
[0] => 4[1] => 12
)
[price] => Array(
[0] => 5[1] => 13
)
[address] => Array(
[0] => 6[1] => 14
)
)
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (7/9) Adapting the parser to our catalogAdapting the parser to our catalog
******************* Final data structure ******************Array(
[0] => product Object(
[name] => Textil [mname] => Bazar [price] => 19.99 [address] => India
)
[1] => product Object(
[name] => Red glass dragon [mname] => Mirota [price] => 22.99 [address] => Indonesia
)
)
Textil Bazar 19.99 India
Red glass dragon Mirota 2.99 Indonesia
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (7/9) Adapting the parser to our catalogAdapting the parser to our catalog
******************* Final data structure ******************Array(
[0] => product Object(
[name] => Textil [mname] => Bazar [price] => 19.99 [address] => India
)
[1] => product Object(
[name] => Red glass dragon [mname] => Mirota [price] => 22.99 [address] => Indonesia
)
)
Textil Bazar 19.99 India
Red glass dragon Mirota 2.99 Indonesia
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (8/9)Some observations
• Problems– It still doesn’t use DTD’s– If there is more than one tag with the same name
• E.g., <product> <name> … and <client> <name>…– It is ignoring the tag <manufacturer>, placing its fields as
<product> fields.
• Further improvements– Keep track of the current position in the tree (the level, the name of the
elements) and use the full path as field name to solve tag ambiguity– Define a Manufacturer Class, and include it as a field of Product
• The Class structure is highly dependable on the XML structure to be parsed
– Generic Solution: create a DTD parser in PHP that gives as output the PHP code to parse the XML
• Too complex!
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LPHP for XML parsing (9/9)Adapting this to the assignment
• Parsing complex XML files is harder in PHP– The parser has to be adapted to the
XML structure• Why to use PHP for XML
parsing?– When you don’t have
control over the server and you can’t have a XSLT engine installed.
– The XML extension is usually installed in most webservers.
– The XSLT extension is hardly installed in the webservers.
• In the assignment you can decide which option (PHP/XSLT) to use.
STORE WEBSITESTORE WEBSITE
HTMLHTMLXMLXML
XSLTXSLT
PHPPHP
ee Com
mer
ce C
ours
e: P
HP,
C
omm
erce
Cou
rse:
PH
P, P
ostg
reSQ
LPo
stgr
eSQ
L&
XM
L&
XM
LUseful links
• HTML tutorial– [1] http://www.w3.org/MarkUp/#tutorials
• Internet Programming course slides (PHP,HTML,CSS,XML…)– [2] http://www.cs.uu.nl/docs/vakken/inp/iplectures.html
• PHP manual– [3] http://nl.php.net/
• PHP tutorial– [4] http://www.juicystudio.com/tutorial/php/index.asp
• PHP Coding Standard– [5] http://alltasks.net/code/php_coding_standard.html
• PHP and PostgreSQL functions– [6] http://nl.php.net/manual/en/ref.pgsql.php
• PostgreSQL documentation– [7a] http://www.cs.uu.nl/sw/pkg/postgresql/doc/– [7b] http://www.postgresql.org/
• PHP and XML functions– [8] http://nl.php.net/manual/en/ref.xml.php
To download the source files of the examples:To download the source files of the examples:http://www.http://www.cscs..uuuu..nlnl/people//people/javierjavier/teaching/PHP/teaching/PHP--lesles--files.zipfiles.zip