28
PHP Tutorial Learn with Concepts [Type the abstract of the document here. The abstract is typically a short summary of the contents of the document. Type the abstract of the document here. The abstract is typically a short summary of the contents of the document.] 7/1/2013

Php web development

Embed Size (px)

DESCRIPTION

This is the some useful topics about php

Citation preview

Page 1: Php web development

PHP Tutorial Learn with Concepts

[Type the abstract of the document here. The abstract is typically a short summary of

the contents of the document. Type the abstract of the document here. The abstract

is typically a short summary of the contents of the document.]

7/1/2013

Page 2: Php web development

PHP Tutorial 2013

1

Introduction to PHP :

The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases.

PHP is basically used for developing web based software applications.

This tutorial helps you to build your base with PHP.

What is PHP….?

PHP files can contain text, HTML, JavaScript code, and PHP code PHP code are executed on the server, and the result is returned to

the browser as plain HTML PHP files have a default file extension of ".php" Much of its syntax is borrowed from C, Java and Perl with a couple

of unique PHP-specific features thrown in.

What’s it do..?

It is also helpful to think of PHP in terms of what it can do for you. PHP will allow you to :

Reduce the time to create large websites.

PHP can generate dynamic page content

PHP can create, open, read, write, and close files on the server

PHP can collect form data

HP can send and receive cookies

PHP can add, delete, modify data in your database

PHP can restrict users to access some pages on your website

PHP can encrypt data

Page 3: Php web development

PHP Tutorial 2013

2

Why PHP….?

PHP runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)

PHP has support for a wide range of databases

PHP is easy to learn and runs efficiently on the server side

PHP is free.

What You Should Know ……?

Before you continue you should have a basic understanding of the following:

HTML JAVASCRIPT

Installation:

What Do You Need…?

To start using PHP, you can :

Find a web host with PHP and MySQL support Install a web server (Wamp Server) on your own PC, and then

install PHP and MySQL.

Basic PHP Syntax :

A PHP script can be placed anywhere in the document.

A PHP script starts with ‘<?php’ and ends with ‘?>’

This is called canonical PHP tags.

Page 4: Php web development

PHP Tutorial 2013

3

<?php

//PHP code goes here

?>

Short-Open tages :

Short or Short-open tags look like this :

<?.........?>

Example Simple HTML & PHP Page:

<html>

<head>

<title>My First PHP Page</title>

</head>

<body>

<?php

echo “WELCOME TO PHP”; // for printing the message use ‘echo’

?>

</body>

</html>

Page 5: Php web development

PHP Tutorial 2013

4

PHP Variables :

As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).

Variable can have short names (like x and y) or more descriptive names (age, carname, totalvolume).

Rules for PHP variables:

A variable starts with the ’$’ sign, followed by the name of the variable.

A variable name must begin with a letter or the underscore character.

A variable name can only contain alpha-numeric characters and underscores (A-z,0-9,_)

A variable name should not contain spaces. Variable names are case sensitive ($y and $Y are two different

variables)

Creating (declaring ) PHP Variables :

PHP has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

$txt="Hello world!"; $x=5;

After the execution of the statements above , the variable $txt will hold the value Hello world! , and the variable x will hold the value 5.

Note : When you assign a text value to a variable, put quotes around the value.

Page 6: Php web development

PHP Tutorial 2013

5

PHP is Loosely Typed Language

In the above example , notice that we did not have to tell PHP which data type the variable is.

PHP automatically converts the variable to the correct data type, depending on its value.

In a strongly typed programming language, we will have to declare (define) the type and name of the variable before using it.

PHP Variable Types :

PHP has a total of eight data types which we use to construct our variables:

Integers: are whole numbers, without a decimal point, like 4195. Doubles: are floating-point numbers, like 3.14159 or 49.1. Booleans: have only two possible values either true or false. NULL: is a special type that only has one value: NULL. Strings: are sequences of characters, like 'PHP supports string

operations.' Arrays: are named and indexed collections of other values. Objects: are instances of programmer-defined classes, which can

package up both other kinds of values and functions that are specific to the class.

esources: are special variables that hold references to resources external to PHP (such as database connections).

Page 7: Php web development

PHP Tutorial 2013

6

PHP Strings :

String variables are used for values that contain characters.

After we have created a string variable we can manipulate it. A string can be used directly in a function or it can be stored in a variable.

In the example below, we create a string variable called txt, then we assign the text "Hello world!" to it. Then we write the value of the txt variable to the output :

Example :

<?php $txt="Hello world!"; echo $txt; ?>

Note: When you assign a text value to a variable, remember to put single or double quotes around the value.

PHP Concatenation Operator :

There is only one string operator in PHP.

The concatenation operator (.) is used to join two string values together.

The example below shows how to concatenate two string variables together:

Page 8: Php web development

PHP Tutorial 2013

7

<?php

$txt1="Hello....!";

$txt2="How are you...?";

//echo $txt1."".$txt2;

echo $txt1.$txt2;

?>

OUT PUT : Hello….!How are you…?

PHP strlen() function :

Sometimes it is useful to know the length of a string value.

The strlen() function returns the length of a string, in characters.

The example below returns the length of the string "Hello world!":

Example :

<?php

echo strlen(“Hello World!”);

?>

OUTPUT :

The Output of the code above will be : 12

Page 9: Php web development

PHP Tutorial 2013

8

NOTE : strlen() is often used in loops or other functions, when it is important to know

when a string ends. (i.e. in a loop, we might want to stop the loop after the last

character in a string).

PHP strops() function :

The strops() function is used to search for a character or a specific text within a string.

If a match is found, it will return the character position of the first match. If no match is

found, it will return FALSE.

Example :

<?php

echo strpos("Hello world!","world");

?>

The output of the code above will be : 6.

NOTE : The position of the string "world" in the example above is 6. The

reason that it is 6 (and not 7), is that the first character position in the

string is 0, and not 1

PHP Operator Types :

What is Operator…?

Operators are used to manipulate or perform operations on variables

and values.

PHP language supports following type of operators.

Arithmetic Operators

Assignment Operators

Incrementing/Decrementing Operator

Page 10: Php web development

PHP Tutorial 2013

9

Comparison Operator

Logical Operator

PHP Arithmetic Operator :

Operator Name Description

x+y Addition Sum of x and y

x-y Subtraction Difference of x and y

x*y Multiplication Product of x and y

x/y Division Quotient of x and y

x% y Modulus Remainder of x divided by y

-x Negation Opposite of x

a.b Concatenate Concatenate two strings

PHP Assignment Operator :

Assignment Same as Description

x=y x=y The left operator gets set to the value of the expression on the right

x+=y x=x+y Addition

x-=y x=x-y Subtraction

x*=y x=x*y Multiplication

x/=y x=x/y Division

x%=y x=x%y Modulus

a.=b a=a.b Concatenate two String

Page 11: Php web development

PHP Tutorial 2013

10

PHP Comparison Operator :

Operator Name Description x == y Equal True if x is equal to y

x === y Identical

True if x is equal to y, and they are of same type

x != y Not equal True if x is not equal to y

x <> y Not equal True if x is not equal to y

x !== y Not identical True if x is not equal to y, or they are not of same type

x > y Greater than True if x is greater than y

x < y Less than True if x is less than y

x >= y Greater than or equal to

True if x is greater than or equal to y

x <= y Less than or equal to True if x is less than or equal to y

PHP Logical Operator :

Operator Name Description x and y And True if both x and y are true

x or y Or True if either or both x and y are true

x xor y Xor True if either x or y is true, but not both

x && y And True if both x and y are true

x || y Or

True if either or both x and y are true

! x Not

True if x is not true

Page 12: Php web development

PHP Tutorial 2013

11

PHP ARRAY :

An array is a data structure that stores one or more similar type of values

in a single value. For example if you want to store 100 numbers then

instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed

using an ID c which is called array index.

There are three different kind of arrays and each array value is accessed

using an ID c which is called array index.

Indexed arrays - Arrays with numeric index

Associative arrays - Arrays with named keys

Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Array :

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0):

Method 1:

$fruits=array(“Mango”,”Banana”,”Orange”);

Method 2:

$fruits[0]=”Mango”;

$fruits[1]=”Banana”;

$fruits[2]=”Orange”;

Page 13: Php web development

PHP Tutorial 2013

12

Example :

<?php

$fruits=array(“Mango”,”Banana”,”Orange”);

echo “I like”.$fruits[2].””;

?>

PHP Associative Array :

Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age=array(“Ajay”=>”23”,”Rohit”=>”25”,”Amit”=>”21”);

OR

$age[‘Ajay’]=”23”;

$age[‘Rohit’]=”25”;

$age[‘Amit’]=”21”;

Example :

<?php

$age=array("Amit"=>"23","Rohit"=>"25","Ajay"=>"21");

echo "Rohit is" .$age['Rohit']. "years old";

?>

Page 14: Php web development

PHP Tutorial 2013

13

PHP Decision Making :

The if, elseif ...else and switch statements are used to take decision based on the different condition.

PHP if Statement : the if statement is used to execute some code only if a specified condition is true.

Syntax :

if (condition) { code to be executed if condition is true; }

Example :

<?php

$a=20;

if($a>18){

echo "the variable is greater than 18";

}

?>

PHP If….else Statement : Use the if....else statement to execute

some code if a condition is true and another code if the condition is false.

Page 15: Php web development

PHP Tutorial 2013

14

Syntax :

if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }

Example :

<?php

$a=20;

if($a>18){

echo "the variable is greater than 18";

}else{

echo “the variable is less than 18 ”

?>

PHP else if Statement : If you want to execute some code if one of several conditions are true use the elseif statement.

Syntax :

if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true;

Page 16: Php web development

PHP Tutorial 2013

15

else code to be executed if condition is false;

Example :

<?php

$a=20;

if($a>25){

echo "the variable is greater than 18";

}else if ($a<22)

{

echo "the variable is less than 22";

}else{

echo "no match found";

}

?>

Switch Statement : Use the switch statement to select one of many blocks of code to be executed.

Page 17: Php web development

PHP Tutorial 2013

16

Syntax :

Switch(n)

{

Case “label1” :

//code to be executed if n=label1;

Break;

Case “label2” :

//code to be executed if n=label2;

Break;

Default :

//code to be executed id n is different from both label1 and label2;

}

Example :

<?php $favcolor="blue"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break;

Page 18: Php web development

PHP Tutorial 2013

17

case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, or green!"; } ?>

PHP Loops : Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.

PHP for loop : loops through a block of code a specified number of times.

Syntax :

for (initialization; condition; increment) { code to be executed; }

Example :

<?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br>"; } ?>

OUTPUT :

The number is 1 The number is 2 The number is 3 The number is 4 The number is 5

Page 19: Php web development

PHP Tutorial 2013

18

PHP While loop : loops through a block of code while a specified condition is true.

Syntax :

while(condition){

//code to be executed

}

Example :

<?php $i=1; while($i<=5) { echo "The number is " . $i . "<br>"; $i++; } ?>

OUTPUT :

The number is 1 The number is 2 The number is 3 The number is 4 The number is 5

PHP do… while loop : loops through a block of code once, and then repeats the loop as long as a specified condition is true.

Page 20: Php web development

PHP Tutorial 2013

19

Syntax :

do { code to be executed; } while (condition);

Example :

<?php $i=1; do { $i++; echo "The number is " . $i . "<br>"; } while ($i<=5); ?>

OUTPUT :

The number is 2 The number is 3 The number is 4 The number is 5 The number is 6

Page 21: Php web development

PHP Tutorial 2013

20

PHP foreach loop : The foreach loop is used to loop through arrays.

Syntax :

foreach ($array as $value) { code to be executed; }

Example :

<?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br>"; } ?>

OUYPUT :

one

two

three

PHP Function :

A function will be executed by a call to the function.

Syntax :

function functionName()

{

code to be executed;

}

Page 22: Php web development

PHP Tutorial 2013

21

PHP function guidelines:

Give the function a name that reflects what the function does

The function name can start with a letter or underscore (not a

number)

Example :

<?php

function writeName()

{

echo "Rohit";

}

echo "My name is ";

writeName();

?>

OUTPUT :

My name is Rohit

PHP Function –Return Value :

To let a function return a value, use the return statement.

Example :

<?php

function add($x,$y){

$total=$x+$y;

return $total;

Page 23: Php web development

PHP Tutorial 2013

22

}

echo "the sum of 3 and 4 is= ".add(3,4);

?>

In PHP, the predefined $_GET variable is used to collect values in a form with method="get".

The $_GET Variable : The predefined $_GET variable is used to collect values in a form

with method="get".

Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.

The GET Method :

The GET method produces a long string that appears in your server logs, in the browser's Location: box.

The GET method is restricted to send upto 1024 characters only.

Never use GET method if you have password or other sensitive information to be sent to the server.

GET can't be used to send binary data, like images or word documents, to the server.

The data sent by GET method can be accessed using QUERY_STRING environment variable.

The PHP provides $_GET associative array to access all the sent information using GET method.

Page 24: Php web development

PHP Tutorial 2013

23

Example :

Create the form user.php

<html>

<head><title></title></head>

<body>

<form action="get.php" method="get">

Name: <input type="text" name="fname">

Age: <input type="text" name="age">

<input type="submit">

</form>

</body>

</html>

Now create the php file name as welcome.php

Welcome <?php echo $_GET["fname"]; ?>.<br> You are <?php echo $_GET["age"]; ?> years old!

NOTE : When the user clicks the "Submit" button, the URL sent to the server could look something like this:

http://localhost/welcome.php?fname=user_name&age=user_age

The POST Method :

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

Page 25: Php web development

PHP Tutorial 2013

24

The POST method does not have any restrictions on data size to be sent.

The POST method can be used to send ASCII as well as Binary data.

Example :

NOTE : you can use above example by replacing GET method.

DATABASE (MYSQL) :

Database : Database is a collection of real world entities.

Now a days we use relational database management systems (RDBMS) to store and manager huge volume of data. This is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as foreign keys.

RDBMS :

A Relational Database Management System (RDBMS) is a software that:

Enables you to implement a database with tables, columns, and indexes.

Guarantees the Referential Integrity between rows of various tables.

Updates the indexes automatically.

Interprets an SQL query and combines information from various tables.

RDBMS Terminology :

Before we proceed to explain MySQL database system, lets revise few definitions related to database.

Page 26: Php web development

PHP Tutorial 2013

25

1. Database : A database is a collection of tables with related data. 2. Tables : A table is matrix with data. A table in a database looks like

a simple spreadsheet. 3. Column : One column contains data of one and the same kind. 4. Row : A row(tuple or records) is a group of related data. 5. Redundancy : Storing data twice, redundantly to make the system

faster. 6. Primary Key : A Primary Key is unique, not null. 7. Foreign Key : A foreign key is the linking pin between two tables. 8. Index : An index in a database resembles an index at the back of a

book.

Database connectivity :

Use the PHP mysql_connect() function to open a new connection to the MySQL server.

Open a Connection to the MySQL Server

Syntax :

$con=mysql_connect(host,username,password,dbname)

Host : Either a hostname or an IP address

Username : The MySQL username

Password : The Password to login with

Dbname : The default database name to be used when performing queries.

Page 27: Php web development

PHP Tutorial 2013

26

Close a Connection :

The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function:

Syntax :

mysql_close($con);

Create a database in mysql :

Syntax :

Create database db_name;

Example : if you want to create the database name as store then the query will be :

create database store;

Create a Table in database :

Syntax :

create table tbl_name(f1 varchar(50),f2 varchar……);

Example :

create table product (p_id int (11),p_name varchar(50),p_price varchar(50));

Page 28: Php web development

PHP Tutorial 2013

27

Insert the values in Table :

Syntax : The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO tbl_name VALUES (value1, value2, value3,...);

The second form specifies both the column names and the values to be inserted:

INSERT INTO tbl_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

Select Data from a database table :

Syntax :

select * from tbl_name;