You are on page 1of 55

TRAINING REPORT

On

PHP
Submitted for partial fulfillment Of B. Tech.

in
COMPUTER SCIENCE AND ENGINEERING
SUBMITTED TO: Er.Ankush (Lect in CSE/IT Deptt.) SUBMITTED BY:Hitender Dalal 1609068 CSE 4
th

Year

(Affiliated to Kurukshetra University, Kurukshetra) (Approved by AICTE, New Delhi) 1

CERTIFICATE
I hereby certify that the work presented in this report entitled PHP submitted in the partial fulfillment of the requirement for the award of degree of Bachelor from Computer Science Engineering, from JIND INSTITUTE OF TECHNOLOGY,JIND and is an authentic record of my own work.

Hitender Dalal 1609068

ACKNOWLEDGEMENT
With profound sense of gratitude, I take it as a highly esteemed privilege in expressing my sincere thanks to my supervisor and guide Miss SUMAN for her technical guidance, sound advice, excellent supervision, valuable suggestions and ever available help during entire course of training. Without her wise counsel and able guidance, this training would not have been completed in this manner. I owe my sincere gratitude to all the faculties of CSE Jind Institute of Engineering and Technology, Jind for their encouragement and unfailing interest in sincere suggestions from time to time in this work. Finally, I owe to the almighty who gave me to carry out this work with sincerity and dedication.

Hitender Dalal 1609068

TABLE OF CONTENTS
1. INTRODUCTION....................................................................................................6-7 1.1 HISTORY OF PHP..........................................................................................6 1.2 FEATURES OF PHP.......................................................................................7 2. HTML........................................................................................................................8-9 2.1 HYPERTEXT MARKUP LANGUAGE.......................................................8 2.2 TAGS IN HTML...............................................................................................8 2.3 FEATURES OF HTML...................................................................................9 2.4 BREAKS USED IN HTML.............................................................................9 3. KEY CONCEPTS OF HTML.................................................................................10-11 3.1 ELEMENTS.....................................................................................................10 3.2 TAGS................................................................................................................10 3.3 ATTRIBUTES NAD VALUES......................................................................10 3.4NESTING..........................................................................................................11 4. TAGS AND CODING...............................................................................................12-15 5. PHP.............................................................................................................................16-17 5.1 HYPERTEXT PRE-PROCESSOR................................................................16 6. CONTROL STRUCTURE IN PHP.........................................................................18-30 6.1 CONDITIONAL CONTROL STRUCTURE................................................18 6.2 UNCONDIONAL CONTROL STRUCTURE...............................................26 6.3 REPEATITION LOOPS...................................................................................28 7. $GET AND $POST VARIABLES.............................................................................31-32 7.1 $GET VARIABLE............................................................................................31 7.2 $POST VARIABLE...........................................................................................31 7.3 DIFFERENCE BETWEEN GET AND POST................................................32 8. SESSION , COOKIES AND FILE UPLOADING....................................................33-35 8.1 PHP SESSION VARIABLE...............................................................................33 8.2 STARTING A PHP SESSION............................................................................33 8.3 PHP COOKIE.......................................................................................................33 8.4 CREATING A PHP COOKIE............................................................................34 8.5 RETRIVING A COOKIE...................................................................................34 8.6 DELETING A COOKIE.....................................................................................34 8.7 PHP FILE UPLOADING....................................................................................35 8.8 CREATING AN UPLOAD FILE.......................................................................35

9. JAVASCRIPT...............................................................................................................36-37 9.1 INTRODUCTION TO JAVASCRIPT...............................................................36 9.2 JAVASCRIPT FORM VALIDATION...............................................................37 9.3 REQUIRED FEILDS............................................................................................37 10. CASCADING STYLE SHEETS (CSS).....................................................................38-39 10.1 INTRODUCTION TO CSS................................................................................38 10.2 STYLE SHEET...................................................................................................38 10.3 EXTERNAL STYLE SHEET............................................................................38 10.4 INTERNAL STYLE SHEET.............................................................................39 10.5 INLINE STYLES................................................................................................39 11. MySQL DATABASE...................................................................................................40-54 11.1 MySQL DATABASE..........................................................................................40 11.2 CONNECTING A DATABASE........................................................................44 11.3 PHP MySQL INSERT INTO.............................................................................45 11.4 PHP MySQL SELECT.......................................................................................48 11.5 DISPLAY RESULT IN AN HTML TABLE....................................................49 11.6 PHP MySQL THE WHERE CLAUSE.............................................................50 11.7 PHP MySQL ORDER BY KEYWORD............................................................51 11.8 PHP MySQL UPDATE.......................................................................................52 11.9 PHP MySQL DELETE.......................................................................................54 12. REFRENCES...................................................................................................................55

1. INTRODUCTION
PHP stands for HYPERTEXT PRE-PROCESSOR . But It stands for HPP then why it still called PHP . We came to know about it in the history of PHP.

1.1 HISTORY OF PHP


PHP originally stands for Personal Home Page. PHP was developed by RASMUS LERDOOF in 1994 . He firstly use it for his personal use at home . In 1997 market name for PHP came HYPERTEXT PRE-PROCESSOR . First version of PHP (2.0) came in 1997 then . 3.0 came in 1999 . Latest version of PHP is 5.3.5 . In September of year 1994 , Rasmus expanded upon PHP and - for a short time - actually dropped the PHP name. Now referring to the tools as FI (short for "Forms Interpreter"), the new implementation included some of the basic functionality of PHP as we know it today . It had Perl-like variables, automatic interpretation of form variables, and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent . The code got another complete makeover, and in April of 1996, combining the names of past releases, Rasmus introduced PHP/FI. This second-generation implementation began to truly evolve PHP from a suite of tools into a programming language in its own right. It included built-in support for DBM, mySQL, and Postgres95 databases, cookies, userdefined function support, and much more. That June, PHP/FI was given a version 2.0 status. An interesting fact about this, however, is that there was only one single full version of PHP 2.0. When it finally graduated from beta status in November, 1997, the underlying parsing engine was already being entirely rewritten . A Netcraft survey as of May, 1998, indicated that nearly 60,000 domains domains reported having headers containing "PHP," indicating that the host server did indeed have it installed. This number equated to approximately 1% of all domains on the Internet at the time. Despite these impressive figures, the maturation of PHP/FI was doomed to limitations; while there were several minor contributors, it was still primarily developed by an individual.

1.2 FEARTURES OF PHP


It is very SIMPLE . Open source language . It have HTML embedded scripting . It is Server sided . In PHP we create COOKIES . In PHP we create SESSIONS . It have Object Oriented Programming Structure . It is Portable . SAFE MODE : The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now . DEALING WITH XFORMS : Xforms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even nontraditional media such as PDF documents . The first key difference in XForms is how the form is sent to the client . It is used by millions of Websites today PHP can be used with all kind of DBMS . PHP is free . PHP files are saved with the extension .php in the server files .

SYNTAX OF PHP
< ? php

?>

2. HTML
2.1 HYPER TEXT MARKUP LANGUAGE
HYPER - non linear TEXT - any simple text MARKUP - tags and linking LANGUAGE - any language for programming. It is used to generate web page . HTML, an initialism of Hypertext Markup Language, is the predominant markup language for web pages. It provides a means to describe the structure of textbased information in a document by denoting certain text as headings, paragraphs, lists, and so on.

2.2 TAGS IN HTML


Tags are the keywords in angle brackets used for scripting in HTML Tags are of two types : Paired : Tags which have an opening and closing . for e.g. <html> </html> <body> </body> <p> </p> Unpaired : Tags need not to be closed for e.g. <br> need not to be closed . <img> need not to be closed

2.3 FEATURES OF HTML


Client sided language Not case sensitive Interpret language Easy to use and understand HTML is free Almost all browsers support HTML Most search engine friendly language Most development tool support HTML Basic language for Website designing Server free language It is Static . No site can be structured without the knowledge of HTML . Not much effective features can be added to the site if made only with HTML . No knowledge of programming is needed to do coding in HTML . HTML originally was developed with the intent of defining the structure of documents (headings, paragraphs, lists, and so forth) to facilitate the sharing of scientific information between researchers .

2.4 BREAKS USED IN HTML


In HTML we use 3 types of breaks : 1. br :- It is an unpaired tag used for single line break . 2. p :- It is a paired tag and used for more than one line break . 3. &nbsp :- It stands for non-breaking space and it gives only one character space . It is not a tag .

3. KEY COCEPTS OF HTML


The first step toward understanding and working with HTML is learning the basic terms that describe most of the functions of this language. You will come across these terms repeatedly as you use HTML and if you understand them, you will have progressed a long way toward comprehending HTML, not to mention XHTML.

3.1 ELEMENTS
All HTML pages are made up of elements. Think of an element as a container in which a portion of a page is placed. Whatever is contained inside the element will take on the characteristics of that element. For example, to identify a heading on a page, you would enclose it in a heading element <h1> </h1>. If you want to create a table, you put the table information inside the table element <table> </table>. To construct a form, you need the form element <form> </form>.

3.2 TAGS
Often, youll find the terms element and tag used interchangeably. Its fairly common, but not strictly accurate. An element is made up of two tags: an opening tag and a closing tag. Although it might seem somewhat picky to make this distinction, when you begin to work with XHTML (Extensible Hypertext Markup Language), it will be a very important difference to remember. If you get into the habit of distinguishing elements and tags from the very beginning, youll save yourself some confusion down the line. All tags are constructed the same way. The tag begins with a less than sign (<), then the element name, followed by a greater than sign (>). For example, an opening tag for the paragraph element would look like this: <p>. The only difference in a closing tag is that the closing tag includes a slash (/) before the element name: </p>. Your content goes between the tags. A simple paragraph might look like this: <p>This is an HTML paragraph.</p> Some elements do not use closing tags because they do not enclose content. These are called empty elements. For example, the line break element <br> does not require a closing tag. In the case of empty elements, add a closing slash after the element name, like this: <br />. When a browser sees the slash, it will recognize the element as one that does not need a separate, closing tag.

3.3 ATTRIBUTES AND VALUES


Attributes are another important part of HTML markup. An attribute is used to define the characteristics of an element and is placed inside the elements opening tag. For example, to specify the size of an image or graphic on your page, you would use the image element <img /> along with the height and width attributes:

10

<img height=" " width=" " />

Be sure to notice that an equals sign and a set of quotation marks follow both the height and the width attributes. Thats because attributes need values to go with them. In the case of the preceding illustration, you might add a value of 200 to cause your image to display at a size of 200 x 200 pixels:
<img height="200" width="200" />

values work together with attributes to complete the definition of an elements characteristics. An easy way to think of how attributes and values work together is to compare them with nouns and adjectives. A noun names something; an adjective describes it. An attribute names a characteristic; a value describes it. Imagine that you are trying to identify a persons hair color with a markup language. Hair would be the element, color the attribute, and red the value. You might write such a description as follows:
<hair color="red">Red-headed Person</hair>

3.4 NESTING
Often you will want to apply more than one element to a portion of your page. An essential concept to understand is nesting. Nesting simply means that elements must never overlap. Properly nested elements are contained inside one another, as in the following:
<a> <b> <c> </c> </b> </a>

Sometimes its easier to understand the concept if the elements are displayed vertically, like this:
<a><b><C> </c> </b> </a>

The following elements, on the other hand, are overlapping:


<a> <b> </a> <c> </b> </c>

Web browsers displaying an HTML page can be pretty forgiving if your elements are not properly nested; however, overlapped elements can create garbled results, particularly if you are trying to construct frames or tables. Also, when you become familiar with XHTMLs stricter standards, youll discover that overlapping elements are an absolute no-no.

11

4. TAGS AND CODING


<html> : It is the main starting tag in HTML . All the coding of the webpage is done in this tag . <title> : It displays the name or title of the Webpage . <head> : It stands for heading and is used for giving the heading in the Webpage . <body> : All the scripting of the content of the Webpage is mainly done in this tag . <h1> to <h6> : These are tags in which we script our text . These are 6 tags in which h1 has the biggest font and h6 has the smallest . <marquee> : It is used to scroll the text . It have following attributes : Direction - left , right , up , down Behavior - alternate , slide , scroll scroll amount onmouseover onmouseout

<font> : Text can also be written in this tag with more features than h1 tag . We can provide different attributes in this tag : size color face

<div> : It is used for page division . It creates a new section in the Webpage . Mainly used in CSS styling . <p> : It is used for more than one line break and text can also be written in this text . <b> : It is used to make text bold
12

<i> : It is used to make text italic <u> : It is used to underline the text <a> : It stands for anchor tag and used to give links in it . Another page link can be given in this tag . <img> : It is used to add image in the webpage . It have different attributes : align height width

<table> : It is used to create the table in the Webpage . It have following attributes align height width bgcolor border bordercolor cellpadding cellspacing

<th> : It stands for table header . This tag is used in table tag . <tr> : It stands for table row . This tag is used in table tag <td> : It stands for table data . This is used in table tag

13

<form> : It is used for creating an HTML form of user input . It can contain one or more of the following form elements : <input> <textarea> <button> <select> <option> <optgroup> <feildset> <label> It have following attributes : accept accept - charset action autocomplete enctype method name target novalidate

Type of input in form tag : login password checkbox radio image button
14

submit reset <frameset> : HTML frames allow authors to present documents in multiple views, which may be independent windows or subwindows . Attribute of this tag are : rows cols

<frame> : Source for the frame is given in this tag . <iframe> : It is used to give a fixed frame space in a Webpage . Attributes of iframe are : height width align scrolling name

<ol> : It stands for ordered list . Attributes are : 1 I A

<ul> : It stands for unordered list . Attributes are : circle square fill circle

<li> : It is used for listing items in ordered and unordered lists . <bgsound> : This tag is used for adding music files .
15

5. PHP
5.1 HYPERTEXT PRE - PROCESSOR
1) In PHP we can't use any data types . 2) In PHP we use $ symbol before variable initialization . 3) In PHP we use three statement to print the output . print : It is used to print single statement . printf : It is used to print numeric value . echo : It is used for both purposes .

4) PHP configuration file is php.ini 5) We save PHP files in wamp > www > .......

A simple program
< ? php $a = 10 ; $b = "c" ; $c = "Hello Welcome To PHP" ; echo $a , "<br>" ; echo $b , "<br>" ; echo $c , "<br>" ;

?>

16

OUTPUT FOR CODING

17

6. CONTROL STRUCTURE IN PHP


In PHP control structures are divided in 3 parts :

6.1 CONDITIONAL CONTROL STRUCTURES


In this type of control structure conditions are applied .

if :
In conditional control structures we have only one condition and one statement . If the condition is true then the statement is printed else statement is terminated . syntax : if (condition) { statement ; } < ? php $a = 10 ; if ($a > 0) { echo " $a is greater than zero " ; } ?>

18

19

if else :
In this we have one condition but two statements . If the condition is true then the statement 1 is printed and if condition is false statement 2 is printed in the output . syntax : if (condition) { statement 1 ; } else { statement 2 ; } <?php $a=-10; if($a>0) { echo"$a is greater than zero"; } else { echo"$a is smaller than zero"; } ?>

20

21

nested if : If within a if is called nested if . If our outer condition is true then control goes to inner if part else control goes to if - else part . <?php $a=20; $b=30; $c=10; if($a>$b) { if($a>$c) { echo"$a is greater"; } else { echo"$c is greater"; } } else if($b>$c) { echo"$b is greater"; } else {
22

echo"$c is greater"; } ?>

23

ladder if : There are if statements one after another forming a if - else ladder . <?php $marks=75; if($marks>90) { echo"grade-A"; } else if($marks>75) { echo"grade-B"; } else if($marks>60) { echo"grade-C"; } else { echo"student fail"; } ?>

24

25

6.2 UNCONDITIONAL CONTROL STRUCTURE


In this control structure our statement is not dependent on the condition instead it depend on the expression . It is further divided into 2 parts : switch break

<?php $ch='t'; switch($ch) { case 'm': echo"monday"; break; case't': echo"tuesday"; break; case 'w': echo"wednesday"; break; deafault: echo"invalid"; } ?>
26

27

6.3 REPEATITION LOOPS


Loops are the circular structure with no escape without their termination . In this we use three types of loops . while : In this first we check condition then statement is executed . <?php $a=1; while($a<10) { echo $a,"<br>"; $a++; } ?>

28

do while : First statement is executed then condition is checked . Any statement will be executed atleast once. <?php $a=1; do { echo $a,"<br>"; $a++; } while($a>10); ?>

29

for loop : <?php for($a=1;$a<=10;$a++) { echo $a,"<br>"; } ?>

30

7. $GET AND $POST VARIABLES


The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input . In PHP if we send the data from one page to another than we use these variables .

7.1 $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. Example <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL sent to the server could look something like this: http://www.w3schools.com/welcome.php?fname=Peter&age=37 The "welcome.php" file can now use the $_GET variable to collect form data (the names of the form fields will automatically be the keys in the $_GET array): Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!

7.2 $POST VARIABLE


The predefined $_POST variable is used to collect values from a form sent with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Note: However, there is an 8 Mb max size for the POST method, by default (can be
31

changed by setting the post_max_size in the php.ini file). Example <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL will look like this: http://www.w3schools.com/welcome.php The "welcome.php" file can now use the $_POST variable to collect form data (the names of the form fields will automatically be the keys in the $_POST array): Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old

7.3 DIFFERENCE BETWEEN GET AND POST


In GET method the value of textbox is displayed in the URL bar but in POST method it is not displayed GET method is not secured method but POST method is secured method GET method is fast method but POST method is not much fast .

32

8. SESSION , COOKIES AND FILE UPLOADING


8.1 PHP SESSION VARIABLE
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.

8.2 STARTING A PHP SESSION


Before you can store user information in your PHP session, you must first start up the session. Note: The session_start() function must appear BEFORE the <html> tag: <?php session_start(); ?> <html> <body> </body> </html>

8.3 PHP COOKIES


A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values .

33

8.4 CREATING A PHP COOKIE


The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax: setcookie(name, value, expire, path, domain);

8.5 RETRIVING A COOKIE


The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>

8.6 DELEATING A COOKIE


When deleting a cookie you should assure that the expiration date is in the past. Delete example: <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>

34

8.7 PHP FILE UPLOADING


With PHP it is possible to upload files on server . In PHP we use single method to upload the data . move_uploaded_file( ) We can upload the file to the temporary location or any loaction we select .

8.8 CREATING AN UPLOAD FILE FORM


To allow users to upload files from a form can be very useful. Look at the following HTML form for uploading files: <html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>

35

9. JAVASCRIPT
9.1 INTRODUCTION TO JAVASCRIPT
JavaScript is THE scripting language of the Web. JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary

compilation) Everyone can use JavaScript without purchasing a license

Example: <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <script type="text/javascript"> document.write("<p>My First JavaScript</p>"); </script> </body> </html>

36

9.2 JAVASCRIPT FORM VALIDATION


JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be: has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?

9.3 REQUIRED FEILDS


The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted: function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } } JavaScript has become one of the most popular programming languages on the web. Initially, however, many professional programmers denigrated the language because its target audience was web authors and other such "amateurs", among other reasons. The advent of Ajax returned JavaScript to the spotlight and brought more professional programming attention. The result was a proliferation of comprehensive frameworks and libraries, improved JavaScript programming practices, and increased usage of JavaScript outside of web browsers, as seen by the proliferation of server-side javascript platforms.

37

10. CASCADING STYLE SHEET (CSS)


10.1 INTRODUCTION TO CSS
CSS stands for Cascading Style Sheets. Styles define how to display HTML elements. Styles were added to HTML 4.0 to solve a problem. External Style Sheets can save a lot of work. External Style Sheets are stored in CSS files.

10.2 STYLE SHEETS


There are three ways of inserting a style sheet: External style sheet Internal style sheet Inline style

10.3 EXTERNAL STYLE SHEETS


An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> An external style sheet can be written in any text editor. The file should not contain any html tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is shown below: hr {color:sienna;}
38

p {margin-left:20px;} body {background-image:url("images/back40.gif");}

10.4 INTERNAL STYLE SHEETS


An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section of an HTML page, by using the <style> tag, like this: <head> <style type="text/css"> hr {color:sienna;} p {margin-left:20px;} body {background-image:url("images/back40.gif");} </style> </head>

10.5 INLINE STYLES


An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method sparingly! To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left margin of a paragraph: <p style="color:sienna;margin-left:20px">This is a paragraph.</p> CSS frameworks are pre-prepared libraries that are meant to allow for easier, more standardscompliant styling of web pages using the Cascading Style Sheets language. Layout-grid-related CSS frameworks include Blueprint, 960 grid, and YUI CSS grids. Like programming and scripting language libraries, CSS frameworks are usually incorporated as external .css sheets referenced in the HTML <head>. They provide a number of ready-made options for designing and laying out the web page.
39

11. MySQL DATABASE


11.1 MySql DATABASE
MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows. Databases are useful when storing information categorically. A company may have a database with the following tables: "Employees", "Products", "Customers" and "Orders".

Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons": LastName FirstName Address Hansen Ola Svendson Tove PettersenKari City

Timoteivn 10 Sandnes Borgvn 23 Sandnes Storgt 20 Stavanger

The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City).

Queries A query is a question or a request. With MySQL, we can query a database for specific information and have a recordset returned. Look at the following query: SELECT LastName FROM Persons
40

The query above selects all the data in the "LastName" column from the "Persons" table, and will return a recordset like this:

LastName Hansen Svendson Pettersen MySQL is the most popular open-source database system.

Create Database and Tables A database holds one or multiple tables. Create a Database The CREATE DATABASE statement is used to create a database in MySQL. Syntax: CREATE DATABASE database_name To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example creates a database called "my_db": <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); }

if (mysql_query("CREATE DATABASE my_db",$con))


41

{ echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } mysql_close($con); ?>

Create a Table The CREATE TABLE statement is used to create a table in MySQL. Syntax: CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... ) To learn more about SQL, please visit our SQL tutorial. We must add the CREATE TABLE statement to the mysql_query() function to execute the command. Example The following example creates a table named "Persons", with three columns. The column names will be "FirstName", "LastName" and "Age": <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) {
42

die('Could not connect: ' . mysql_error()); }

// Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); }

// Create table mysql_select_db("my_db", $con); $sql = "CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int )";

// Execute query mysql_query($sql,$con);

mysql_close($con); ?> Important: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function.

43

Note: When you create a database field of type varchar, you must specify the maximum length of the field, e.g. varchar(15). mysql_query($sql,$con);

11.2 CONNECTING A DATABASE


The free MySQL database is very often used with PHP. Before you can access data in a database, you must create a connection to the database. In PHP, this is done with the mysql_connect() function. Syntax: mysql_connect(servername,username,password); Parameter servername username Description Optional. Specifies the server to connect to. Default value is "localhost:3306" Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process password Optional. Specifies the password to log in with. Default is ""

Example In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error());
44

} // some code ?>

Closing a Connection The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); }

// some code

mysql_close($con); ?>

11.3 PHP MySQL INSERT INTO


The INSERT INTO statement is used to insert new records in a table. The INSERT INTO statement is used to add new records to a database table. Syntax: It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values: INSERT INTO table_name VALUES (value1, value2, value3,...)

45

The second form specifies both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

To get PHP to execute the statements above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example In the previous chapter we created a table named "Persons", with three columns; "Firstname", "Lastname" and "Age". We will use the same table in this example. The following example adds two new records to the "Persons" table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); }

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)");

mysql_query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire',33)");

mysql_close($con); ?> Insert Data From a Form Into a Database Now we will create an HTML form that can be used to add new records to the "Persons" table. Here is the HTML form:
46

<html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form>

</body> </html> When a user clicks the submit button in the HTML form in the example above, the form data is sent to "insert.php". The "insert.php" file connects to a database, and retrieves the values from the form with the PHP $_POST variables. Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the "Persons" table. Here is the "insert.php" page: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error());
47

} echo "1 record added"; mysql_close($con); ?>

11.4 PHP MySQL SELECT


The SELECT statement is used to select data from a database. Select Data From a Database Table The SELECT statement is used to select data from a database. Syntax: SELECT column_name(s) FROM table_name To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example selects all the data stored in the "Persons" table (The * character selects all the data in the table): <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); }

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName'];


48

echo "<br />"; } mysql_close($con); ?> The example above stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']). The output of the code above will be: Peter Griffin Glenn Quagmire

11.5 DISPLAY THE RESULT IN HTML TABLE


The following example selects the same data as the example above, but will display the data in an HTML table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons"); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> </tr>"; while($row = mysql_fetch_array($result))
49

{ echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); ?> The output of the code above will be: Firstname Lastname Glenn Peter Quagmire Griffin

11.6 PHP MySQL THE WHERE CLAUSE


The WHERE clause is used to filter records. The WHERE clause is used to extract only those records that fulfill a Syntax: SELECT column_name(s) FROM table_name WHERE column_name operator value To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example selects all rows from the "Persons" table where "FirstName='Peter'": <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con)
50

specified criterion.

{ die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons WHERE FirstName='Peter'");

while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br />"; } ?> The output of the code above will be: Peter Griffin

11.7 PHP MySQL ORDER BY KEYWORD


The ORDER BY keyword is used to sort the data in a recordset. The ORDER BY keyword sort the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword. Syntax: SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC Example The following example selects all the data stored in the "Persons" table, and sorts the result by the "Age" column: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con)
51

{ die('Could not connect: ' . mysql_error()); }

mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['FirstName']; echo " " . $row['LastName']; echo " " . $row['Age']; echo "<br />"; } mysql_close($con); ?>
The output of the code above will be:

Glenn Quagmire 33 Peter Griffin 35

11.8 PHP MySQL UPDATE


The UPDATE statement is used to update existing records in a table. Syntax: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

52

To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example Earlier in the tutorial we created a table named "Persons". Here is how it looks: FirstName LastName Age Peter Glenn Griffin 35 Quagmire 33

The following example updates some data in the "Persons" table: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("UPDATE Persons SET Age=36 WHERE FirstName='Peter' AND LastName='Griffin'"); mysql_close($con); ?> After the update, the "Persons" table will look like this: FirstName LastName Age Peter Glenn Griffin 36

Quagmire 33

53

11.9 PHP MySQL DELETE


The DELETE FROM statement is used to delete records from a database table. Syntax: DELETE FROM table_name WHERE some_column = some_value To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example Look at the following "Persons" table: FirstName LastName Age Peter Glenn Griffin 35 Quagmire 33

The following example deletes all the records in the "Persons" table where LastName='Griffin': <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("DELETE FROM Persons WHERE LastName='Griffin'"); mysql_close($con); ?>

54

12. REFRENCES
1. http://www.w3schools.com/html/default.asp 2. http://en.wikipedia.org/wiki/HTML 3. http://en.wikipedia.org/wiki/PHP 4. http://php.net/manual/en/index.php 5. http://www.w3schools.com/php/default.asp 6. http://www.w3schools.com/js/default.asp 7. http://en.wikipedia.org/wiki/JavaScript 8. www.w3schools.com/css/ 9. en.wikipedia.org/wiki/Cascading_Style_Sheets 10. en.wikipedia.org/wiki/MySQL 11. www.w3schools.com/php/php_mysql_intro.asp 12. www.w3schools.com/php/php_sessions.asp 13. php.net/manual/en/features.sessions.php 14. php.net/manual/en/function.setcookie.php 15. www.w3schools.com/php/php_cookies.asp 16. php.net/manual/en/features.file-upload.php 17. www.w3schools.com/php/php_file_upload.asp 18. www.w3schools.com/tags/tag_html.asp

55

You might also like