This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Article Home> Articles > PHP > Fundamentals PHP Tutorial PHP is the most popular scripting language on the web. This PHP tutorial will teach you to create dynamic web pages. PHP is known as a server-sided language. The html of page does not make on your computer but you request it and it comes from the server after executing the code.
1/32
04/28/09 04:03:58 An Introduction to PHP
An Introduction to PHP 1. What is PHP and Why do I need it? PHP is the most popular scripting language on the web. PHP is used to create dynamic pages. PHP is known as a server-sided language. The html of a page is not generated on your computer but you request it and it comes from the server after executing the request. The results of the requested page are then displayed in your browser. PHP stands for Hypertext Pre-processor. Later it was named as 'Personal Home Page'.
2. What you need to get started You must have: Apache Web Server or Windows IIS PHP Installer 4.43 (Download from: http://www.php.net/downloads.php) MySql Installer (Download from: http://dev.mysql.com/downloads/) Any Text Editor (Macromedia DreamWeaver,Notepad)
3. Installing and testing PHP and MySql Click on the installers to install the PHP and Mysql and follow the installer instructions to complete the setup. Once you done open your editor and write echo Tutorial from VisualBuilder; ?>
Save the file by pressing (Ctrl+s) with extension test.php and save in C:Inetpubwwwroottest.php in WINDOWS IIS or C:apachehttpdocstest.php in Tom Cat Apache Server
Point your browser to http://localhost/test.php you will see Tutorial from VisualBuilder,if this does not come up then check your installation of PHP or see do you save the file under the directory as listed above.
2/32
04/28/09 04:03:58
3/32
04/28/09 04:03:58 Getting Started With Variables
Getting Started With Variables 1. PHP Syntax The PHP script strat with less than and question mark signs () and end with question mark and greater than sign (?>) any code will be written between these tags. echo My First Page of PHP; echo I am learning PHP; ?> 2. What is a Variable? A variable is a container that stores the information that you want to use on the page for later use. You can save text and numbers in variable. As the name shows it’s a variable so you can change values (text or number) in variable. Any text with $ sign will become variable in php $myNum=1; $myText=This is my first variable text.; ?>
Variables are case sensitive.
3. Joining direct text and variable data
$myText=This is my first variable test.; $myJoinText=$myText. This is the joing text with variable.; $myJoinText2=This is Text1.. This is Text2.; echo $myJoinText; 4/32
04/28/09 04:03:58 echo $myJoinText2;
Note The . dot sign used to concat the two variables or strings.
4. Adding up in PHP To add one number to another, the + symbol is used in PHP. If you see 4 + 3, it means add 3 into 4. echo 2+2; $a=4; $b=3; echo $a+$b; $add=$a+$b; echo The added values are = .$add; ?>
5. Subtraction To subtract one number from another, the - symbol is used in PHP. If you see 4 - 3, it means subtract 3 from 4. echo 2-2; $a=4; $b=3; echo $a-$b; $subtract=$a-$b; echo The subtracted values are = .$subtract; ?> 6. Multiplication 5/32
04/28/09 04:03:58 To multiply two numbers, the * symbol is used in PHP. If you see 4 * 3, it means multiply 3 with 4. echo 2*2; $a=4; $b=3; echo $a*$b; $multiply=$a*$b; echo The multiplicated values are = .$multiply; ?> 7. Division To divide two numbers, the / symbol is used in PHP. If you see 4 / 2, it means divide 4 by 2. echo 2/2; $a=4; $b=2; echo $a/$b; $divide=$a/$b; echo The divided values are = .$divide; ?>
6/32
04/28/09 04:03:58 Comments in PHP
Comments in PHP Single line comments are // This will not execute on server
Multiline Comments /* This whole Paragrapgh Will not Execute On the Server */
7/32
04/28/09 04:03:58 Operators
Operators 1. Comparison Operators
== Has the same value e.g $variable == $variable2 != Does NOT have the same value e.g $variable != $variable2 > Less than e.g $variable > $variable2 < Greater than e.g $variable < $variable2 >= Greater than or equals to e.g $variable >= $variable2 <= Less than or equals to e.g $variable <= $variable2
Conditional Logic 1. If Statements You learn that variables are used to store some information that you can use later whenever required,you can save text and numbers. You store information so that you can do something with them. If you have stored a username in a variable and need to check if this is a correct username. For this you need to use IF statement. if(condition) { // Start with { and end with } and any thing written between these two {} are execute under if condition }
04/28/09 04:03:58 if( $username != Doree ) { echo If condition OK as our variable has Nemo saved in it and we are comparing Nemo with Doree that are two different strings so we are in if statement.; } if( $number == 2031 ) // Did not go into this statement { echo ; }
== (Double equal sign) used to compare two strings or numbers. != (Sign of Exclamation and equal sign) used to compare if two strings or numbers are not equal to each other 2. if ... else IF ELSE statement used when your IF statement doesnot comes true than you use the ELSE part. For example if the values of two variables are same you want to print out TRUE (i.e variables have same values) and if the values of the two variabales are not equal (i.e variables have different values) than you want to print FALSE,here ELSE part of IF used. $username = Nemo; $number = 19051981; 9/32
3. if ... else if $usaFlag = 0; $ukFlag = 1; if ( $usaFlag == 1 ) { echo ; } else if ( $ukFlag == 1 ) { echo ; } else { echo No value equal to 1 found.; } ?>
11/32
04/28/09 04:03:58 The Switch Statement
The Switch Statement We tested two variables in the previous examples. A flag of a country was shown on the screen,depending on the value inside of the variable. A long list of if and else … if statements were used. A better option,if you have only one variable to test,is to use something called a switch statement. To see how switch statements work,check the following example. $ukFlag ='1'; switch ( $ukFlag ) { case '0': echo ; break; case '1': echo ; break; default: echo No Flag Shown; } ?>
switch ($ukFlag) You Start with the word 'Switch' then variable name you want to check.
case 'What you want to check for': The word 'case' is used before each value you want to check for. These value are: 0 and 1. These are the values we need after the word 'case'. After the the text or variable you want to check for,a colon is needed ( : ) and code written after this.
break; You need to tell PHP to Break out of the switch statement. If you don't,PHP will simply drop down to the next case and check that. Use the word 'break' to get out of the Switch statement.
12/32
04/28/09 04:03:58 default: If nothing case matched than the value that you have under default statement will execute.
Boolean Values A Boolean value is one that is in either of two states. They are known as True or False values,in programming. True is usually given a value of 1,and False is given a value of zero. You set them up just like other variables $trueValue = 1; $falseValue = 0; You can replace the 1 and 0 with the words true and false (without the quotes). But a note of caution,if you do. Try this script out,and see what happens: $true_value = true; $false_value = false; echo true_value = . $true_value; echo false_value = . $false_value; ?>
16/32
04/28/09 04:03:58 Working with HTML Forms
Working with HTML Forms 1. The HTML Form A BASIC HTML FORM
6. Getting values from a Text Box
When you submit the form butoon you can get the value of textbox on the same page or the page whose name you given in action tag of form. The value of text field will gte by the name of the textfield that is username echo $_POST[username]; // If form submit by POST method echo $_GET[username]; // If form submit by GET method echo $_REQUEST[username]; // Works for both POST and GET method of form ?>
7. Checking if the Submit button was clicked 17/32
04/28/09 04:03:58 We are assuming that form is submitted by POST method if (isset($_POST['Submit'])) { }
// isset() Its a php function that check wheather a variable is set or empty. ?>
5. Do ... While loops This type is loop is almost identical to the while loop,except that the condition comes at the end.
do statement while (condition)
The difference is that your statement gets executed at least once. In a normal while loop,the condition could be met before your statement gets executed. 6. The break statement Break statement is used to stop the loop while loop is running to complete its round.
$counter = 1; while ($counter < 11) { echo counter = . $counter . ; if($counter==7) break; $counter ; } ?> 1. For Loops The loop goes round and round. Loops are used to redo the same action again and again until the limit you set. 19/32
04/28/09 04:03:58
for (start value; end value; update expression) {}
$counter = 0; for($start=1; $start < 11; $start ) { $counter = $counter 1; echo $counter . ; } // $start equivalent to the $start = $start 1; // $start-- equivalent to the $start = $start - 1; ?>
4. While Loops The structure of a while loop is more simple than a for loop,because you’re only evaluating the one condition. The loop goes round and round while the condition is true. When the condition is false,the programme breaks out of the while loop.
while (condition) { statement }
$counter = 1; while ($counter < 11)
20/32
04/28/09 04:03:58 Arrays in PHP
Arrays in PHP 1. What is an Array? Variable can hold a single value at a time whereas an array is like a special variable,which can hold more than one number,or more than one string,at a time.
?> 5. Arrays and For Each foreach ($contactInfo as $key_name => $key_value) { echo Key = . $key_name . Value = . $key_value . ; } ?>
6. Sorting Array values There may be times when you want to sort the values inside of an array. There are many functions in php to sort values in an array. Some of them are;
asort($names) – Sort an array and maintain index association arsort($names) - Sort an array in reverse order and maintain index association rsort($names) – Sorts an array in reverse order krsort($names) - Sort an array by key in reverse order ?>
7. Random Keys from an Array $numbers = array(1 => 1,2 => 3,3 => 5,4 => 7,5 => 9,6 => 11); $random_key = array_rand($numbers,1); echo $random_key; ?>
2. Trimming White Space trim( Test ); // Remove white space from both sides of a string ltrim( Test ); // Remove white space from left side of a string rtrim( Test ); // Remove white space from right side of a string ?>
5. Splitting a line of text $full_name = Jaydra,Joe,Elizabeth,Abby,Vilma,Laura; $names = explode(,,$full_name); // Returns an array by breaking string with , sign echo $names[0]; ?>
25/32
04/28/09 04:03:58 Create your own Functions
Create your own Functions 1. An Introduction to Functions A function is just a piece of code,that you want to use not once but again and again. Functions save you from writing the code again and again. A function always return a value.
2. Variable scope and functions
function function_name( ) { }
3. Functions and Arguments You can pass variable to your functions by typing them inside of the round brackets of the function name. function myFunction($variable1,$variable2) { echo $variable1; } // Using Function $variable1=Some Text; $variable2=100; myFunction($variable1,$variable2); ?>
4. Getting values out of functions Getting some calculated value from function.
26/32
04/28/09 04:03:58 Get a discout value. $spent_money = 150; echo calculate($spent_money);
5. HTTP Header() Function header(Location: http://www.visualbuilder.com/); ?>
6. The INCLUDE( ) Function include somefile.txt ; ?>
27/32
04/28/09 04:03:58 Date and Time Functions in PHP
Date and Time Functions in PHP 1. The date( ) function Use to get date. $today = date('m-d-Y'); echo $today; // Print Current Month - Current Day - Current Year echo date('d-m-Y'); echo ('Y-m-d'); ?> 2. Using the date( ) function There are numbers of parameters that you can use in date function.
format character Day
Description
Example returned values
--Day of the month,2 digits with leading zeros A textual representation of a day,three letters Day of the month without leading zeros
d D j l (lowercase A full textual representation of the day of the week 'L') ISO-8601 numeric representation of the day of the week N (added in PHP 5.1.0) S English ordinal suffix for the day of the month,2 characters w
Numeric representation of the day of the week
z
The day of the year (starting from 0) --ISO-8601 week number of year,weeks starting on Monday (added in PHP 4.1.0) --A full textual representation of a month,such as January or March Numeric representation of a month,with leading zeros A short textual representation of a month,three letters Numeric representation of a month,without leading zeros Number of days in the given month --Whether it's a leap year ISO-8601 year number. This has the same value as Y,except that if the ISO week number (W) belongs to the previous or next year,that year is used instead. (added in PHP 5.1.0)
Week W Month F m M n t Year L o
28/32
--01 to 31 Mon through Sun 1 to 31 Sunday through Saturday 1 (for Monday) through 7 (for Sunday) st,nd,rd or th. Works well with j 0 (for Sunday) through 6 (for Saturday) 0 through 365 --Example: 42 (the 42nd week in the year) --January through December 01 through 12 Jan through Dec 1 through 12 28 through 31 --1 if it is a leap year,0 otherwise. Examples: 1999 or 2003
04/28/09 04:03:58 Y y Time a A B g G h H i s Timezone
A full numeric representation of a year,4 digits A two digit representation of a year --Lowercase Ante meridiem and Post meridiem Uppercase Ante meridiem and Post meridiem Swatch Internet time 12-hour format of an hour without leading zeros 24-hour format of an hour without leading zeros 12-hour format of an hour with leading zeros 24-hour format of an hour with leading zeros Minutes with leading zeros Seconds,with leading zeros ---
Examples: 1999 or 2003 Examples: 99 or 03 --am or pm AM or PM 000 through 999 1 through 12 0 through 23 01 through 12 00 through 23 00 to 59 00 through 59 --Examples: UTC,GMT,Atlantic/Azores 1 if Daylight Saving Time,0 otherwise. Example: 0200
e
Timezone identifier (added in PHP 5.1.0)
I (capital i)
Whether or not the date is in daylight saving time
O
Difference to Greenwich time (GMT) in hours Difference to Greenwich time (GMT) with colon between hours Example: 02:00 and minutes (added in PHP 5.1.3) Timezone setting of this machine Examples: EST,MDT ... Timezone offset in seconds. The offset for timezones west of UTC is always negative,and for those east of UTC is always -43200 through 50400 positive.
P T Z
Full --Date/Time c ISO 8601 date (added in PHP 5)
--2004-02-12T15:19:21 00:00 Example: Thu,21 Dec 2000 16:01:07 0200
r
RFC 2822 formatted date
U
Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
29/32
See also time()
04/28/09 04:03:58 Working With Files In PHP
PHP and MySQL Manipulate a MySQL Database 1. Access a MySQL database with PHP code $con=mysql_connect(ServerName,Username,Password); $db=mysql_select_db(DatabaseName,Connection Idenfier);
// Server name is the name of server that you are working on 99% it is localhost // Username is the name of user of mysql database // Password is the password of mysql database // Database Name is the name of database that you created in mysql ?>
2. Reading records from a MySQL database $con=mysql_connect(localhost,root,mypass); $db=mysql_select_db(mydb,$son);
$result=mysql_query(Select * from myTable) or die(mysql_error()); while($row=mysql_fetch_array($result)) { echo $row[fieldName]. ; echo $row[fieldName2]. ; } // mysql_query() used to execute the sql 30/32
04/28/09 04:03:58 // die() If some error occur than this function triggers // mysql_error() Shows mysql error // mysql_fetch_array() gets the records in an array // mysql_num_rows() returns the number of rows found ?>
3. Adding records to a MySQL database mysql_query(Insert into myTable set fieldName='Test Value',fieldName2='Test Value2' );
// This will insert a record to myTable // mysql_insert_id(); If an autoincremnet field is set in table than it returns the id of last entered record. // mysql_affected_rows() Returns the number of rows affected by Add,Delete and Updat operation ?> 4. Updating a record in a table mysql_query(Update myTable set fieldName='Test Value',fieldName2='Test Value2' where id='1' ); ?>
5. Deleting a record in a table mysql_query(delete from myTable where id='1' ); ?> 6. Using WHERE to limit the data returned mysql_query(select * from myTable where id='1' ); ?>
31/32
04/28/09 04:03:58
Date entered : 11th Sep 2007 Rating :No Rating Submitted by : visualbuilder
Copyright Visualbuilder.com 1999-2006 Document created date: 28 Apr 2009