SlideShare a Scribd company logo
1 of 18
Introduction to PHP and
PostgreSQL
CSC 436 – Fall 2008
Slides based on PHP manual “Getting Started” from
http://www.php.net/tut.php
PHP - Overview
Introduction
Tutorial
Installation
PostgreSQL with PHP
Extended example
Introduction
PHP (recursive acronym for "PHP:
Hypertext Preprocessor")
 widely-used Open Source general-purpose
scripting language
 especially suited for Web development
 can be embedded into HTML.
<html>
<head>
<title>Example</title>
</head>
<body>
<?php echo "Hi, I'm a PHP script!"; ?>
</body>
</html>
See this example here:
What can PHP do?
Server-side scripting
 most traditional and main target field
 need three things to make this work
 PHP parser (CGI or server module)
 webserver – with connected PHP installation
 web browser
Command line scripting
 PHP script to run it without any server or browser
 need the PHP parser to use it this way
Writing client-side GUI applications
 not the best language to write windowing
applications
 use PHP-GTK to write such programs
Tutorial
What do I need?
Your first PHP-enabled page
Something Useful
Dealing with Forms
What's next?
What do I need?
Assume that your server has support
for PHP activated and that all files
ending in .php are handled by PHP
Create your .php files and put them in
your web directory and the server will
magically parse them for you
No need to compile anything
Develop locally
 install a web server, such as Apache
 install PHP
 install a database as well, such as
PostgreSQL.
First PHP-enabled page
Create a file named hello.php
Put it in your web servers directory
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo "<p>Hello World</p>"; ?>
</body>
</html>
Use your browser to access the file
Something useful
check what sort of browser the person viewing
the page is using
 check the user agent string that the browser sends
as part of its HTTP request
 stored in a variable
 always start with a dollar-sign in PHP
 $_SERVER["HTTP_USER_AGENT"].
 $_SERVER is a special reserved PHP variable that
contains all web server information
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>
</body>
</html> (see this file)
Variables
Variables represented by a dollar sign
followed by the name of the variable
 name is case-sensitive.
 name starts with a letter or underscore,
followed by any number of letters, numbers, or
underscores
 type is assigned by value
<?php
$var = "Bob";
$Var = "Joe";
echo "$var, $Var"; // outputs "Bob, Joe"
$x = 1;
$x = ‘abc’; // type can change if value changes
$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; // valid; starts with an underscore
?>
Arrays
created by the array() language-
construct
takes a certain number of comma-
separated key => value pairs
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?> (see it here)
Arrays (cont.)
<?php // Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);
// Now delete every item, but leave the array
// itself intact:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);
// Append an item (note that the new key is 5,
// instead of 0 as you might expect).
$array[] = 6;
print_r($array);
// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?> (see result here)
Dealing with forms
HTML Forms (GET and POST)
 form is submitted to a PHP script
 information from that form is
automatically made available to the
script
 forms.php
<form action="foo.php" method="POST">
Name: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" name="submit"
value="Submit me!">
</form>
Forms – foo.php
<?php // Available since PHP 4.1.0
print $_POST['username'];
print $_REQUEST['username'];
import_request_variables('p', 'p_');
print $p_username;
// Available since PHP 3. As of PHP 5.0.0, these long
// predefined variables can be disabled with the
// register_long_arrays directive.
print $HTTP_POST_VARS['username'];
// Available if the PHP directive register_globals = on.
// As of PHP 4.2.0 the default value of
// register_globals = off.
// Using/relying on this method is not preferred.
print $username; ?> (see result here)
Another forms example
info_form.php
<form action=“show_answers.php” method="POST">
Your name: <input type="text" name="name" />
Your age: <input type="text" name="age" />
<input type="submit">
</form>
show_answers.php
Hi
<?php echo $_POST["name"]; ?>.
You are <?php echo $_POST["age"]; ?> years old.
(see results here)
Installation
PHP is installed on the Linux servers in
the CSC department
You can install it on your own machine
if you want
Refer to the PHP manual for instructions
on installation
http://www.php.net/manual/en/install.php
PosgreSQL with PHP
Assume the following database table and
data:
CREATE TABLE employees
( id tinyint(4) DEFAULT '0' NOT NULL AUTO_INCREMENT,
first varchar(20),
last varchar(20),
address varchar(255),
position varchar(50),
PRIMARY KEY (id),
UNIQUE id (id));
INSERT INTO employees VALUES
(1,'Bob','Smith','128 Here St, Cityname',
'Marketing Manager');
INSERT INTO employees VALUES
(2,'John','Roberts','45 There St ,Townville',
'Telephonist');
INSERT INTO employees VALUES
(3,'Brad','Johnson','1/34 Nowhere Blvd, Snowston',
'Doorman');
PostgreSQL Example (cont)
<html>
<body>
<?php
$db = pg_connect(“dbname=sam user=sam password=iam")
or die(“Couldn’t Connect: “.pg_last_error($db));
$query=“SELECT * FROM employees”;
$result = pg_query($db,$query)
or
die(“Error in query: $query.”.pg_last_error($db));
$rows = pg_num_rows($result);
if ($rows > 0) {
for ($i=0; $i<$rows; $i++){
$my_row = pg_fetch_array($result, $i, PGSQL_ASSOC);
printf("First Name: %s",$my_row[“first”]);
printf("Last Name: %s", $my_row[“last“]);
printf("Address: %s", $my_row[“address“]);
printf("Position: %s",$my_row["position“]);
printf(“n”);
}
}
pg_close($db);
?>
</body>
</html>
Extended Example – Toy Catalog
Toy Catalog – as described in class
Assume database tables created
Assume data inserted into data
Start with html form page

More Related Content

Similar to php_postgresql.ppt

Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfShaimaaMohamedGalal
 
GettingStartedWithPHP
GettingStartedWithPHPGettingStartedWithPHP
GettingStartedWithPHPNat Weerawan
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009cwarren
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.pptGiyaShefin
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingAhmed Swilam
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)Guni Sonow
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to phpjgarifuna
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.pptMercyL2
 

Similar to php_postgresql.ppt (20)

Php mysql
Php mysqlPhp mysql
Php mysql
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
 
GettingStartedWithPHP
GettingStartedWithPHPGettingStartedWithPHP
GettingStartedWithPHP
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
PHP-Part4
PHP-Part4PHP-Part4
PHP-Part4
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
PHP Basic
PHP BasicPHP Basic
PHP Basic
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
introduction_php.ppt
introduction_php.pptintroduction_php.ppt
introduction_php.ppt
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
18.register login
18.register login18.register login
18.register login
 

Recently uploaded

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 

Recently uploaded (20)

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

php_postgresql.ppt

  • 1. Introduction to PHP and PostgreSQL CSC 436 – Fall 2008 Slides based on PHP manual “Getting Started” from http://www.php.net/tut.php
  • 3. Introduction PHP (recursive acronym for "PHP: Hypertext Preprocessor")  widely-used Open Source general-purpose scripting language  especially suited for Web development  can be embedded into HTML. <html> <head> <title>Example</title> </head> <body> <?php echo "Hi, I'm a PHP script!"; ?> </body> </html> See this example here:
  • 4. What can PHP do? Server-side scripting  most traditional and main target field  need three things to make this work  PHP parser (CGI or server module)  webserver – with connected PHP installation  web browser Command line scripting  PHP script to run it without any server or browser  need the PHP parser to use it this way Writing client-side GUI applications  not the best language to write windowing applications  use PHP-GTK to write such programs
  • 5. Tutorial What do I need? Your first PHP-enabled page Something Useful Dealing with Forms What's next?
  • 6. What do I need? Assume that your server has support for PHP activated and that all files ending in .php are handled by PHP Create your .php files and put them in your web directory and the server will magically parse them for you No need to compile anything Develop locally  install a web server, such as Apache  install PHP  install a database as well, such as PostgreSQL.
  • 7. First PHP-enabled page Create a file named hello.php Put it in your web servers directory <html> <head> <title>PHP Test</title> </head> <body> <?php echo "<p>Hello World</p>"; ?> </body> </html> Use your browser to access the file
  • 8. Something useful check what sort of browser the person viewing the page is using  check the user agent string that the browser sends as part of its HTTP request  stored in a variable  always start with a dollar-sign in PHP  $_SERVER["HTTP_USER_AGENT"].  $_SERVER is a special reserved PHP variable that contains all web server information <html> <head> <title>PHP Test</title> </head> <body> <?php echo $_SERVER["HTTP_USER_AGENT"]; ?> </body> </html> (see this file)
  • 9. Variables Variables represented by a dollar sign followed by the name of the variable  name is case-sensitive.  name starts with a letter or underscore, followed by any number of letters, numbers, or underscores  type is assigned by value <?php $var = "Bob"; $Var = "Joe"; echo "$var, $Var"; // outputs "Bob, Joe" $x = 1; $x = ‘abc’; // type can change if value changes $4site = 'not yet'; // invalid; starts with a number $_4site = 'not yet'; // valid; starts with an underscore ?>
  • 10. Arrays created by the array() language- construct takes a certain number of comma- separated key => value pairs <?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1 ?> (see it here)
  • 11. Arrays (cont.) <?php // Create a simple array. $array = array(1, 2, 3, 4, 5); print_r($array); // Now delete every item, but leave the array // itself intact: foreach ($array as $i => $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, // instead of 0 as you might expect). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?> (see result here)
  • 12. Dealing with forms HTML Forms (GET and POST)  form is submitted to a PHP script  information from that form is automatically made available to the script  forms.php <form action="foo.php" method="POST"> Name: <input type="text" name="username"><br> Email: <input type="text" name="email"><br> <input type="submit" name="submit" value="Submit me!"> </form>
  • 13. Forms – foo.php <?php // Available since PHP 4.1.0 print $_POST['username']; print $_REQUEST['username']; import_request_variables('p', 'p_'); print $p_username; // Available since PHP 3. As of PHP 5.0.0, these long // predefined variables can be disabled with the // register_long_arrays directive. print $HTTP_POST_VARS['username']; // Available if the PHP directive register_globals = on. // As of PHP 4.2.0 the default value of // register_globals = off. // Using/relying on this method is not preferred. print $username; ?> (see result here)
  • 14. Another forms example info_form.php <form action=“show_answers.php” method="POST"> Your name: <input type="text" name="name" /> Your age: <input type="text" name="age" /> <input type="submit"> </form> show_answers.php Hi <?php echo $_POST["name"]; ?>. You are <?php echo $_POST["age"]; ?> years old. (see results here)
  • 15. Installation PHP is installed on the Linux servers in the CSC department You can install it on your own machine if you want Refer to the PHP manual for instructions on installation http://www.php.net/manual/en/install.php
  • 16. PosgreSQL with PHP Assume the following database table and data: CREATE TABLE employees ( id tinyint(4) DEFAULT '0' NOT NULL AUTO_INCREMENT, first varchar(20), last varchar(20), address varchar(255), position varchar(50), PRIMARY KEY (id), UNIQUE id (id)); INSERT INTO employees VALUES (1,'Bob','Smith','128 Here St, Cityname', 'Marketing Manager'); INSERT INTO employees VALUES (2,'John','Roberts','45 There St ,Townville', 'Telephonist'); INSERT INTO employees VALUES (3,'Brad','Johnson','1/34 Nowhere Blvd, Snowston', 'Doorman');
  • 17. PostgreSQL Example (cont) <html> <body> <?php $db = pg_connect(“dbname=sam user=sam password=iam") or die(“Couldn’t Connect: “.pg_last_error($db)); $query=“SELECT * FROM employees”; $result = pg_query($db,$query) or die(“Error in query: $query.”.pg_last_error($db)); $rows = pg_num_rows($result); if ($rows > 0) { for ($i=0; $i<$rows; $i++){ $my_row = pg_fetch_array($result, $i, PGSQL_ASSOC); printf("First Name: %s",$my_row[“first”]); printf("Last Name: %s", $my_row[“last“]); printf("Address: %s", $my_row[“address“]); printf("Position: %s",$my_row["position“]); printf(“n”); } } pg_close($db); ?> </body> </html>
  • 18. Extended Example – Toy Catalog Toy Catalog – as described in class Assume database tables created Assume data inserted into data Start with html form page