Programming PHP and MySQL on Windows Platform

Download Report

Transcript Programming PHP and MySQL on Windows Platform

Programming PHP and MySQL
on Windows Platform
A Crash Course
Presented by Connie Zhou
Abacus Biocomputing Systems
To Capstone Teams
©2005 Connie Zhou
The Goals of this Course
• Present a high-level view in aspects of
– MySQL key functionalities in data handling
and related SQL queries
– PHP essential characteristics as a programming
language
– The interaction between PHP and MySQL
• Provide resources for information on PHP
and MySQL for your future references
©2005 Connie Zhou
Course Outlines
Prepare Your
Playground
Take a quick tour
in MySQL 4.x.x
landscape
PHP & MySQL
For OOP.
Take a peek into
PHP 5.x.x
House
©2005 Connie Zhou
Let’s Start with…
Prepare Your
Playground
Take a quick tour
in MySQL 4.x.x
landscape
PHP & MySQL
For OOP.
Take a peek into
PHP 5.x.x
House
©2005 Connie Zhou
Build Your Programming Environment
To build your programming
environment, install the
following software according
to listed sequence:
1. Install Web Server Apatch 2.0
2. Install MySQL 4.x.x database server
3. Install PHP 5.x.x as Apache module
4. Install HTLM-Kit
©2005 Connie Zhou
Install Apache
• It’s free. The latest stable version is 2.0.53
• It runs on Windows, Linux, Mac OS, FreeBSD,
and most flavors of Unix.
• Download a binary version from
http:// httpd.apache.org to save time and energy.
• Then, start Apache and verify your success of
Apache installation.
• See the Apache Web site (http://httpd.apache.org)
for more information
©2005 Connie Zhou
This screen tells you that you did right after you type
http://localhost in the URL text box of your browser.
©2005 Connie Zhou
Install MySQL 4.x.x
• Check its existence on your computer before install it.
– Is it Running? Look for an icon as a traffic signal with a
green light.
– Is it installed? Look for program called WinMySQLadmin,
which starts and stops MySQL, among other functions. It is
probably at C:\mysql\bin directory.
• If Yes, then run it.
• Else, download it from www.mysql.com and install it.
• Get information of installation and operation from web site
http://dev.mysql.com/doc/mysql/en/windows-installation.html.
©2005 Connie Zhou
Install PHP 5.x.x
• It is free. It is gaining popularity as fast as you can
imagine.
• PHP 5.x.x includes many neat stuff. Also it is more
sophisticated for object oriented programming than
its previous version.
• Look for installation information at the URL
http://www.php.net/manual/en/install.windows.php.
©2005 Connie Zhou
Integrate Apache and PHP
In your Apache httpd.conf configuration file, insert the
following lines:
# set up the PHP 5 module for Apache 2.0:
LoadModule php5_module
"c:/php/php5apache2.dll"
AddType application/x-httpd-php .php
# configure the path to php.ini
PHPIniDir “C:/php”
Note: “C:/php” is the directory where your PHP
is installed.
©2005 Connie Zhou
Have PHP Work With MySQL
• Locate and open the php.ini for editing
• Find the following two lines in php.ini:
;extension=php_mysql.dll
;extension=php_mysqli.dll
Remove the semicolon (;) at the beginning of the lines. If
they are not in your php.ini, add them.
• Save the changes in your php.ini file.
• Make sure the two .dll files are in your “c:/php”
directory. If they are not, copy them from
“c:/php/ext/” directory.
• Restart Apache.
©2005 Connie Zhou
Test, Test, This is a Test.
• Create a text file containing only the following
lines:
<?php
phpinfo( );
?>
• Save it as “test.php” in the directory “c:\Program
Files\Apache Group\Apache2\htdocs\”
• In the URL text box of your browser, type:
http://localhost/test.php
That’s it.
©2005 Connie Zhou
If You Do Every Thing Right…
©2005 Connie Zhou
Install HTML-kit 2.0 (Optional)
• It is a good Interactive Development
Environment (IDE) tool kit for web application
file editing.
• It is free! Download it (www.chami.com/htmlkit ) and install it. Play with it.
– If you like it, keep using.
– Else, throw it out of your “windows.”
©2005 Connie Zhou
The HTML-kit User Interface
©2005 Connie Zhou
DOs and DON’Ts
• DO Install PHP as a module for Apache rather than
• For the convenience of future version upgrades, DO
“C:/php” directory in Windows “PATH” variable.
• DO make sure that your “C:/php” directory contains the
following files:
– php_mysql.dll
– php_mysqli.dll
– php5ts.dll
– libmysql.dll
• DON’T install PHP as a CGI extension.
©2005 Connie Zhou
©2005 Connie Zhou
Now let’s …
Build your
programming
environment
Take a quick tour
in MySQL 4.x.x
landscape
PHP & MySQL
For OOP.
Pay PHP 5.x.x
Department
a quick visit
©2005 Connie Zhou
A Quick Tour on Planet MySQL 4
• Key functionalities of
MySQL
• MySQL data type names
• Commenly used MySQL
commands for CRUD
activities.
• Security? Administration?
Not now.
©2005 Connie Zhou
Key Functionalities of MySQL
Handling Data – CRUD
• Create
• Retrieve
• Update
• Delete
Securing Data – Admin
• Accounts
• Permission
• Passwords
• Data Backups
• Data Restorations
Our focus for today is about “Handling Data”.
©2005 Connie Zhou
MySQL Core Data Type Names
MySQL Data Type
Description
CHAR (length)
Fixed-length character string.
VARCHAR(length)
Variable-length character string. (1 ~ 255)
TEXT
Variable-length character string. (max. 64KB)
INT(length)
Integer (-2147483648 ~ + 2147483647). The number can be
displayed is limited by length even though higher numbers are
stored.
INT(length) UNSIGNED
Integer (0 ~ 4294967295). The number can be displayed is
limited by length even though higher numbers are stored.
DECIMAL(length.dec)
Decimal number. E.g. 18.22 has length of 5 and dec of 2.
DATE
Date value with year, month, and date. (YYYY-MM-DD format)
TIME
Time value with hour, minute, and second. (HH:MM:SS format)
DATETIME
Date and time are stored together. (YYYY-MM-DD HH:MM:SS)
ENUM(“val1”, “val2”, …)
Only the values listed can be stored. (max. 65535)
©2005 Connie Zhou
Commonly Used MySQL commands
MySQL Command
Description
Basic Format
CREATE
To create structure of
databases, and tables.
CREATE DATABASE database_name
CREATE TABLE table_name
ALTER
Change the database structure
ALTER TABLE table_name followed by options
See slide “Changes can be done…” for options
ALTER TABLE table_name DROP column_name
SHOW
To display structure of existing
databases.
SHOW DATABASES; SHOW TABLES;
SHOW COLUMNS FROM table_name
DROP
To delete structure of a
database.
DROP DATABASE database_name
DROP TABLE table_name
INSERT
To add data to database, one
row at a time.
INSERT INTO table_name (column_name,
column_name, … column_name) VALUE (value, value,
…, value)
LOAD
To add data to database, one
bunch at a time.
LOAD DATA INFILE “data_file_name” INTO TABLE
table_name followed by optional FIELDS and LINES
clauses.
SELECT
To retrieve data from database
SELECT column_list FROM table_name followed by
optional clauses. See slide “All about SELECT”.
UPDATE
To change information in and
existing row
UPDATE table_name SET column=value, column=value,
… WHERE clause
DELETE
To remove a row
DELETE FROM table_name WHERE clause
©2005 Connie Zhou
Changes can be done with the ALTER Query
Changes
Description
ADD column_name definition
Adds a column; definition includes the data type and optional
definitions.
ALTER column_name
SET DEFAULT value
Changes the default value for a column.
ALTER column_name
DROP DEFAULT
Removes the default value for a column.
CHANGE column_name
New column_name definition
Changes the definition of a column and renames the column;
definition includes the data type and optional definitions.
DROP column_name
Delete a column, including all the data in the column. The data
cannot be recovered.
MODIFY column_name
definition
Changes the definition of a column; definition includes the data
type and optional definitions.
RENAME new_table_name
Renames a table.
©2005 Connie Zhou
SQL Syntax - CREATE
• Create Databases
//Create database named "menagerie". Note that under UNIX, database is case sensitive.
CREATE DATABASE menagerie;
/*Creating a database does not select it for use. You must do that explicitly. To make
menagerie the current database, use this command:*/
USE menagerie
//To verify that the database created, use SHOW DATABASES statement.
SHOW DATABASES;
• Create Tables
//Create a table named “pet” with table layout specification:
CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20),
species VARCHAR(20), sex CHAR(1), birth DATE, death DATE);
//To verify that your table was created the way you expected, use a DESCRIBE
statement:
DESCRIBE pet;
©2005 Connie Zhou
SQL Syntax – LOAD DATA
/*To insert a bunch of rows of data at a time, first, create a text file to contain data to
be loaded. Then load data from the file. (Use \N for NULL fields in the file.) */
LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet;
/*Note that if you created the file on Windows with an editor that uses \r\n as a line
terminator, and comma-delimited, you should use: */
LOAD DATA LOCAL INFILE '/path/pet.txt' INTO TABLE pet
FIELDS TERMINATED BY ‘,'
LINES TERMINATED BY '\r\n';
/*You can specify the column value separator and end of line marker explicitly in
the LOAD DATA statement if you wish, but the defaults are tab and linefeed. These
are sufficient for the statement to read the file pet.txt properly.*/
©2005 Connie Zhou
MySQL Syntax - INSERT
/*When you want to add new records one at a time, the INSERT
statement is useful. The format of INSERT statement is: */
INSERT INTO table_name (column, column, … column)
VALUES (value, value, … value)
/*For example, to insert a row of data in table ‘pet’, use the following
query: */
INSERT INTO pet VALUES
('Puffball','Diane','hamster','f','1999-03-30',NULL);
/*Note that string and date values are specified as quoted strings here.
Also, with INSERT, you can insert NULL directly to represent a
missing value. You do not use \N like you do with LOAD DATA.*/
©2005 Connie Zhou
MySQL Syntax - UPDATE
//The format of UPDATE statement is:
UPDATE table_name SET column=value, column=value, …
WHERE clause
/*In the SET clause, you list the columns to be updated and the new values to be
inserted. Note that without WHERE clause, the values of the column(s) would
be changed in all rows. */
©2005 Connie Zhou
Kaleidoscope of Retrieving Data
Retrieve data
from multiple tables
by using “JOIN”
and “UNION”
clauses.
Retrieve data
from specific
columns & rows.
Retrieve data
in a specific order
by using “ORDER BY”
and “GROUP”
clauses
©2005 Connie Zhou
Retrieve data
And do math in one
SELECT query.
Retrieve data
from a specific source
by using “WHERE”,
“LIMIT”, and
“DISTINCT”
clauses
MySQL Syntax - SELECT
/*The SELECT statement is used to pull information from a table. Its general
format is:
SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy;
what_to_select indicates what you want to see. This can be a list of columns,
or * to indicate “all columns.''
which_table indicates the table from which you want to retrieve data.
The WHERE clause is optional. If it's present, conditions_to_satisfy specifies
conditions that rows must satisfy to qualify for retrieval. */
SELECT * FROM pet;
SELECT name FROM pet;
// retrieve data from all columns
// retrieve data from “name” column
©2005 Connie Zhou
MySQL Syntax – SELECT with Order
//-- Retrieve data in a specific order –
//sorting by ascending order
SELECT column_list FROM table_name ORDER BY column_name
//sorting by descending order
SELECT column_list FROM table_name ORDER BY DESC
column_name
//The rows that have the same value of column_name are grouped together.
SELECT column_list FROM table_name GROUP BY column_name
©2005 Connie Zhou
MySQL Syntax – SELECT from a Source
//-- Retrieve data from a specific source -//WHERE clause-retrieve data from db objects with certain characteristics
WHERE expression AND|OR expression AND|OR expression…
//LIMIT clause-limit the number of rows from which information is retrieved.
SELECT * FROM table_name LIMIT start_number, number_of_columns;
//DISTINCT clause - requests information from only one row of identical rows.
SELECT DISTINCT column_name FROM table_name;
©2005 Connie Zhou
MySQL Syntax – SELECT
from Multiple Tables
//--Retrieve data from multiple tables-//UNION clause – retrieve rows from one or more tables and stored together,
©2005 Connie Zhou
MySQL Syntax – SELECT
with Math Operations*
SQL Format
Description of Information
SELECT AVG(column_ame)
FROM table_name
Returns the average of all the values in
column_name
SELECT
COUNT(colum_name) FROM
table_name
Returns the number of rows in which column_name
is not blank
SELECT MAX(colum_name)
FROM table_name
Returns the largest value in column_name
SELECT MIN(column_name)
FROM table_name
Returns the smallest value in column_name
SELECT SUM(column_name)
FROM table_name
Returns the sum of all the values in column_name
SELECT SQRT(column_name)
FROM table_name
Returns the square root of each value in the column_name
*For complete list of math operations, refer to www.mysql.com .
©2005 Connie Zhou
MySQL Syntax for Removing Data
//To delete all data from a table:
DELETE FROM table_name
//To delete a row from a table:
DELETE FROM table_name WHERE clause
//To delete a column from a table:
ALTER TABLE table_name DROP column_name
//To remove a whole table:
DROP TABLE table_name
//To remove the whole database:
DROP DATABASE database_name
©2005 Connie Zhou
For more detailed information
about MySQL 4.x.x,
Check out the URL
http://dev.mysql.com/doc/mysql/en/index.html
©2005 Connie Zhou
©2005 Connie Zhou
Shall we now …
Build your
programming
environment
Take a quick tour
in MySQL 4.x.x
landscape
PHP & MySQL
For OOP.
Pay PHP 5.x.x
Department
a quick visit
©2005 Connie Zhou
Take A Peek into PHP House
Unit 1
Variables and Constants
- the elements
Unit 2
Flow Control
- the structure
Unit 4
Built-in Functions
-”factory” made coding
components
Unit 3
User Functions
-custom made coding
components
©2005 Connie Zhou
Unit 1
Variables and Constants
- the elements
©2005 Connie Zhou
What About PHP Variables
• PHP variables are the containers for values.
– They are not type sensitive.
– They are created by PHP automatically if you forget to
create them before you use them.
– They are destroyed at the exit point of PHP program
block in which they have their beings.
– They can be manually destroyed by PHP’s unset( )
function.
• The values that PHP deals with fall into two
categories:
– Number
– String of characters
©2005 Connie Zhou
Want to Name A PHP Variable?
• It likes to follow the money (dollar sign): $variable_name
• It is highly sensitive to cases – treats “U” and “u” distinctively.
• Its name can be as long as the river you know, but why do you
want to trouble yourself?
• It accepts a name starting with a letter or an underscore, rejects
a name staring with a number.
• However, it doesn’t mind you slip a number or two in the string
of its name.
• But NO! No strange looking fellows in its name string such as
“*”, “@”, “&”, etc., who belong to the special character club.
• Oh, BTW, make its name meaningful, will you? No “$foo”,
please.
©2005 Connie Zhou
PHP Constants
• They are similar with variables as far as being given a name
and a value to store concerns. However, they are constants.
Once a value is given to them, they hold it till they die!
• They are useful
– when you want to avoid a value been changed by your
program code accidentally.
– Where you want to avoid a value been scattered in your
program code all over the places.
• They are created by “define” statement
define(“constant_name”, “constant_value”);
define(“AGE”, 22);
define(“COMPANY”, “Abacus Biocomputing Systems”);
©2005 Connie Zhou
PHP’s Dealing With Numbers
• PHP can do arithmetic operations, such as “+”, “-”, “*”,
“/”, and “%”, on numbers.
• PHP does “*” and “/” before “+” and “-”.
• If other consideration are equal, PHP does arithmetic
operations from left to right.
• Parentheses alters the order in which PHP does arithmetic
operations.
• PHP provides sprint( ) and number_format( ) functions to
store numbers in the way you want it to. They are useful
for handling financial and scientific numbers.
©2005 Connie Zhou
Examples on PHP’s Number Dealing
// -- examples for arithmetic operation -$num1 = 2;
$num2 = 3;
$sum = $num1 + $num2;
$result = (2 + 3) * 4 – 1;
// On web page you will see:
34,000.00
// -- examples for number handling -// 1. Show me the money
$price = 34000;
$show_price = number_format($price, 2);
echo “$show_price<br>”;
// 2. Display number scientifically
$old_num = 34;
$new_num = sprintf(“%01.2f”, $old_num);
echo “$new_num<br>”;
// On web page you will see:
34.00
©2005 Connie Zhou
PHP’s Dealing with Character Strings
• Character strings can be composed by all characters in a give
character set. They are enclosed in “” or ‘’.
• When a number is used as a character, it can not be arithmetically
operated on.
• PHP handles “” and ‘’ differently.
– ‘’: stores string literally
– “”:evaluates variables and some special characters (\n, \t, etc.) in the string
before stores the string.
– “” and ‘’ can be nested with each other. The outmost one takes the control.
– Use a backslash (\) for escaping a character in a single quoted string.
E.G. $string = ‘It is Connie\’s book.’;
• Concatenate strings by using (.) operator.
E.G. $string1.$string2
• PHP provides a whole array of functions dealing with strings.
©2005 Connie Zhou
Special Attention to Dates and Times
• Dates and times are important for web application. Yet,
computers store them is a so called “timestamp*” format
that tickles human brains.
*Note: The timestamp format is a UNIX Timestamp, which is and integer that is the
number of seconds from Jan. 1, 1970 00:00:00 GMT to the time represented by the
timestamp.
• PHP provides a rich array of functions to just convert the
dates and times between humans and machines.
– The most used function date( ) converts a date or time from the
timestamp into a format of specification.
$my_date = date(“format”, $timestamp);
Where the format is the string specifying the desired date format.
– Use time( ) and strtotime( ) functions to get timestamps.
– Make sure to convert the time into format that compliant with
MySQL. (DATE, DATETIME)
©2005 Connie Zhou
Date Formats*
Symbol Meaning
Example
M
Month in text, abbreviated
Jan
F
Month in text not abbreviated
January
m
Month in numbers with leading zeros
01, 12
n
Month in numbers without leading zeros
1, 12
d
Day of the month; two digits with leading zeros
03, 17
j
Day of the month without leading zeros
3, 17
l
Day of the week in text not abbreviated
Friday, Monday
D
Day of the week in text abbreviated
Fri, Mon
w
Day of the week in numbers
0 (Sun) to 6 (Sat)
Y
Year in four digits
2005
y
Year in two digits
05
g
Hour between 0 and 12 without leading zeros
2, 11
G
Hour between 0 and 24 without leading zeros
3, 15
©2005 Connie Zhou
Date Formats* (Continued)
Symbol
Meaning
Example
h
Hour between 0 and 12 with leading zeros
02, 11
H
Hour between 0 and 24 with leading zeros
03, 15
i
Minutes
00, 59
s
Seconds
00, 59
a
am or pm in lower case
am, pm
A
AM or PM in upper case
AM, PM
*For a complete list of symbols, and date and time related functions, see the
documentation on site http://www.php.net.
©2005 Connie Zhou
Arrays – One of Kind Variables
• Arrays are used to collect relative data
under one variable name.
• An array can be viewed as a list of
key/value pairs.
$states[‘NJ’] = “New Jersey”;
• By default, an array is indexed as 0 based.
©2005 Connie Zhou
Array Handling
Array Creating
Array Value Viewing
Array Sorting
Array Value Retrieving
Array Walking
Array Value Removing
©2005 Connie Zhou
To Create An Array
Do one of the followings:
– $var[index_value] = value;
e.g.
$pet[1] = “cat”;
– $var = array(value, value, … value);
e.g.
$pet = array(“cat”, “dog”, “fish”, “turtle”);
– $var = array(key=>value, key=>value, … key=>value);
e.g.
$states = array(“NJ” => “New Jersey”,
“NY” => “New York”;
“CA” => “California”);
©2005 Connie Zhou
To View An Array
• Use echo statement to see value only
e.g.
echo $states[‘NJ’];
It outputs string “New Jersey”.
• Use print_r( ) statement to view structure and values
e.g.
print_r($states);
It outputs the following
Array
(
[NJ] => New Jersey
[NY] => New York
[CA] => California
)
©2005 Connie Zhou
To Sort An Array
PHP can sort arrays in various ways. The sorting sequence is:
1. Number
2. Uppercase letters
3. Lowercase letters
•
For an array with numbers as keys, use sort( ).
e.g. sort($pets)
This statement sorts by the values and assigns new keys that are the
appropriate numbers.
•
For an array with words as keys, use asort( ).
e.g. asort($states);
This statement sorts the states by value but keep the original keys for
each value.
©2005 Connie Zhou
To Retrieve Values from An Array
• Direct access for individual value
e.g.
$State = $states[‘NJ’];
It puts “New Jersey” into $State;
• Retrieve a group of values using list( ).
e.g.
List($pet1, $pet2) = $pets;
It puts “cat” into $pet1, “dog” into $pet2;
• Retrieve all the values from an array with words as keys
using extract( ).
e.g.
extract($states);
It copies each value into the key;
©2005 Connie Zhou
To Walk Through an Array
• Manually
– current($array): refers to the value currently pointed by the pointer.
– next($array): moves the pointer to the value after the current one.
– previous($array): moves the pointer to the value before the current
one.
– end($array): moves the pointer to the last value in the array.
– reset($array): moves the pointer to the first value in the array.
• foreach loop
foreach($array as $key_name => $value_name)
{
block of statements;
}
©2005 Connie Zhou
Unit 2
Flow Control
- the structure
©2005 Connie Zhou
Elements for Flow Control
SimpleStatements
Statements
Simple
Simple Statements
Conditional
Statements
Loop
Statements
Functions
©2005 Connie Zhou
Simple Statements
• Assignment statement – assigns values to variables
$var = “my book”;
• Increment statement – increases or decreases numbers in variables
$var++; $var--; ++$var; --$var;
$var += 2; $var -= 3; $var *= 4; $var /= 5;
• “echo” statement – produces output to browsers
• “exit” statement – Stops the execution of a program
exit(“message”);
exit(“exiting due to error.”);
• “die” statement – stops the execution of a program
die(“message”);
die(“dying due to error.”);
• “break” statement – exits a loop or a conditional statement
• “continue” statement – alters the course of a loop
• Function call statement – uses stored blocks of statements at any
location in a program.
$result = time(“today”);
©2005 Connie Zhou
Conditional Statements
switch statement
if-else statement
if (conditional expression)
{
block of statements
}
else if (conditional expression)
{
block of statements
}
©2005 Connie Zhou
switch($var){
case value :
block of statements
break;
case value :
block of statements
break;
…
default:
block of statements
break;
}
Conditional Expressions
Expression Description
$a == $b
Are the two values equal?
$a != $b
Are the two values not equal to each other?
$a <> $b
Are the two values not equal to each other?
$a >= $b
Is the first value greater than or equal to the
second value?
$a <= $b
Is the first value less than or equal to the second
value?
$a > $b
Is the first value greater than the second value?
$a < $b
Is the first value less than the second value?
©2005 Connie Zhou
Join Conditional Expressions
• General format for joining conditional expressions:
expression and|or|xor expression and|or|xor expression and|or|xor …
• Meanings of and, or, xor
– and (or &&): Both expressions yield true
– Or (||): One of the expressions or both of the expressions are true
– xor: One of the expressions yields true but not both
• Parentheses alter the operating precedence.
– Use parentheses liberally. Unnecessary parentheses can’t hurt, but
unexpected result can.
©2005 Connie Zhou
Loop Statements
for loop
while loop
for (start_value; end_value; increment)
{
block of statements
}
while (conditional expression)
{
block of statements
}
do..while loop
for each loop
do
{
block of statements
}while(conditional expression)
for each ( )
{
block of statements
}
©2005 Connie Zhou
A Few Notes About Using Loop
• Watch out infinite loops by mistake
– Mistaken an assignment “=“ sign with a
conditionally equal “==“ sign in conditional
expressions
– Leave out increment statements from loops
– Move in value initiating statements into loops
– Mishandling of the index of an array in a loop
• Have control over loops using “break;” and
“continue;” statement in a loop
©2005 Connie Zhou
Function Statements
//Your normal code here
Statement 1;
Statement 2;
…
Statement n;
//Call a function my_function( )
my_function( );
My_function ()
{
block of statements;
}
//continue normal code
Statement n+2;
…
©2005 Connie Zhou
Unit 3
User Functions
-custom made code
components
©2005 Connie Zhou
The Format of A User Function
function function_name(parameter_list)
{
block of statements
return value;
}
Notes:
• The parameter_list is optional.
• The return keyword
–
–
–
–
is optional but nice to have for code clarity.
when it is followed by a value, this value is returned to the calling code.
stops the function and returns to calling code.
is often used for a conditional end to a function. (such as doing a sanity
checking.)
©2005 Connie Zhou
Variables in Functions
• Variables created within a function are stay local
to the function
– They cease to exist as the function terminates.
– They are stored at a different memory location from
those outside of the function yet share the same names.
• To make a function created variable to stick
around after the function finishes its work, use
“global” key word preceding the variable name.
e.g. global $var;
• Variables outside the function CAN NOT be
accessed by the function, unless they are created
as global ones.
©2005 Connie Zhou
Would You Pass Me Some Values, Please? (1)
Passing values to a function in a form of a parameter list*
//Calling Code:
function_name (value1, value2, …valueN);
//Function Code
Function function_name($var1, $var2, …$varN=default value**)
{
block of statements;
return;
}
*The order of the values are important.
**The default value is optional.
©2005 Connie Zhou
Would You Pass Me Some Values, Please?
(2)
Passing values to a function in a form of array*
//Calling Code:
function_name (value_array);
//Function Code
Function function_name(array $var_array)
{
block of statements;
return;
}
*In the case of missing elements, function defaults them into a empty string for
string values and 0 for number values. When too many elements are passed,
function ignores the extra ones.
©2005 Connie Zhou
Would you like something in return?
Pass back value(s) to calling code*
//Calling Code:
$result = function_name (value1, value2, …valueN);
//Function Code
Function function_name($var1, $var2, …$varN=default value)
{
block of statements;
return value;
}
* 1. “return” evaluates the value before pass it back.
2. “return” sends back the value and ends the function.
©2005 Connie Zhou
Unit 4
Built-in Functions
-“factory” made code
components
©2005 Connie Zhou
Let’s Not Invent Wheels Again!
PHP provides built-in functions for almost all sorts of tasks
you would encounter on daily bases.
–
–
–
–
–
–
–
–
–
String handling functions
Date and time functions
Directory functions
File handling functions
FTP functions
Error handling and logging functions
Program execution functions
Calendar functions
Etc, etc, …
See URL http://us2.php.net/manual/en/index.php, you can get
information on all of them.
©2005 Connie Zhou
Most Wanted PHP Built-in Functions
•
•
•
•
•
•
•
•
Communicate with MySQL
Send email
Handle arrays
Check for variables
Use PHP Sessions
Handle strings
Format values
Handle errors and messages
©2005 Connie Zhou
PHP and MySQL Resources
• Official Web Sites
– www.php.net
– www.mysql.com
– http://httpd.apache.org
• PHP and MySQL Resources
– DevShed --Web development tutorial site
– PHP builder --Articles about using PHP
– Black Beans --A very complete list of resources for PHP
– Zend --A lot of info about PHP, including articles, tutorials, code,
forums
– ONLamp PHP section --Articles about using PHP
– ONLamp MySQL section --Articles about using MySQL
©2005 Connie Zhou
©2005 Connie Zhou
©2005 Connie Zhou