Images

Working With PHP - PART I


Working With PHP
This Manual is for developing a web application starting fromScratch , we here discuss every thing from the Beginning and giving you a step by step knowledge , expecting you don’t know about the web development, how can you start web development, what is the requirements & tools, what is theeditors to be used etc.In spite of these we here give a step by step help sectionprint screensInterview Questionsand appendix to actually visualize you to grasp the Logic as well as presentation of actual web development.
This manual, teaches you all flavors of development phases starting from Learning the concept, explaining with examples, basic requirement for a software development, tools software’s, leaning materials and giving the idea of how a software development process going on with providing DFDflowchart E-R diagram, and suitable screen shots and of course project documentation.
And as soon as you follow this, at the last you must feel that the fear of the evil of development will go, and now you have capability to develop software.


Working With PHP
Preface
Software development is a big and endless field, and there is much more to learn in the field always. But the main concern for a newer one who want to develop the software or to be a software developer, but actually he didn’t tried before is, how to start? Where to start? What to start? and what are the basic needs for developing a web application?
Keeping this idea in mind, we provide a platform to you in which we tried to explore the full breadth of the field, which encompasses logic, concepts, procedure, learning and conceptual materials, software requirement, hardware requirement, actual development platform, and everything required for development process in a proper summarized and procedural form.
This tutorial is written for the people who want to learn how to build web applications perfect and in a better way, This manual is not for beginners who don’t know what is Programming Language etc; we expects at least knowledge of the basic concepts of Programming (basic programming).
who knows what’s the Sql Query (select, update insert query etc), and also know what is Html (td, tr and table in html),and know at least the basics knowledge of JavaScript users of all levels to create a web applications quickly and easily.
Basically we are targeting to those people who are at least familiar with the concepts and don’t know how to integrate these in developing a web application.
We teach you a better way to integrating these separate concepts to make a better web application and making you mastering in PHP.
Target of our writing of this is to help the people who join some private Language institutes on paying lots of money, but at the last result is found to be zero. And at last students get frustrated that he/she doesn’t have capability to be a developer.
So don’t get frustrated and carefully follow this book, we assured you after developing  this project with us, you will be a good developer.

Working With PHP
Introduction
The Idea of developing this manual is basically, we know many of the students, who know the basic knowledge about the languages ant script but don’t know how all these integrate in a software development, or any web application.
On targeting this problem we have an idea to we develop this tutorial, where we provide you a complete atmosphere to developed a site (Web application) without any other extra help rather then following our tutorial, Our Basic means to put you at that level at least where you feel to be a good developer.
This Manual is for developing a web application starting from Scratch , we here discuss every thing from the Beginning and giving you a step by step knowledge , expecting you don’t know about the web development, how can you start web development, what is the requirements and what is the basic tools, what is the editors to be used etc.in spite of these we here give a step by step help section, print screens, Interview Questions and appendix to actually visualize you to grasp the Logic as well as presentation of actual web development.
We teach you all from starting, how can you make a Html page , how this will be work on browsers ,how can you add css, how can you apply JavaScript ,how can you connect your page to database and by teaching you these thing , we put you at a complete web application.
This tutorial is basically a approach to teach, actual development work in php, or developing a web application, while you know about the basic concepts such asphp,mysql,html and JavaScript, no matter, you don’t have any knowledge about web application, or any software Development.
This manual, teaches you all flavors of development phases starting from Learning the concept, explaining with examples, basic requirement for a software development, tools software’s, leaning materials and giving the idea of how a software development process going on with providing DFD,flowchart E-R diagram, and suitable screen shots,and of course the documentation of the project too.
And as soon as you follow this, at the last you must feel that the fear of the evil of development will go, and now you have capability to develop software.
Why we learn it
• To know how can I integrate the Php, Html, JavaScript and Mysql to Make a better web    page.

• To know a better development tips

• To know a better way to develop a web application

• Mastering in software

• To Make a Web Application

• To know what is software development process
Benefits
This is the manual where we teaches from scratch ,either person who only know the basic concepts of the languages, to learn these manual, really helps the person basically who are doing preparation for a software development field, Or who are first experienced in a software company and don’t know about the actual scenario of the development.
Through this manual we giving defiantly expertise you the development process, and in the website development, and you no longer be a new to development.

Introduction to Web Technology
Client-Server Technology
About Web Technology
The growth of the World-Wide Web (WWW or simply Web) today is simply phenomenal. Each day, thousands more people gain access to the Internet (upwards of 6 million users at recent estimates). Easy retrieval of electronic information in conjunction with the multimedia capabilities of Web browsers (like Mosaic or Netscape) is what started this explosion.
This section provides information about web technologies that relate to the interface between web servers and their clients. This information includes markup languages, programming interfaces and languages, and standards for document identification and display.
img
As you can see in fig, all of the machines on the Internet can be categorised as two types: servers and clients. Those machines that provide services (like Web servers or FTP servers) to other machines are servers. And the machines that are used to connect to those services are clients.
When you connect to Yahoo at www.yahoo.com to read a page, Yahoo is providing a machine (probably a cluster of very large machines), for use on the Internet, to service your request.
Yahoo is providing a server. Your machine, on the other hand, is probably providing no services to anyone else on the Internet. Therefore, it is a user machine, also known as a client. It is possible and common for a machine to be both a server and a client!

Introduction to Web Technology
Apache Web Server
Is generally recognized as the world's most popular Web server (HTTP server). Originally designed for UNIX servers, the Apache Web server has been ported to Windows and other network operating systems (NOS).
The name "Apache" derives from the word "patchy" that the Apache developers used to describe early versions of their software.
The Apache Web server provides a full range of Web server features, including CGI, SSL, and virtual domains. Apache also supports plug-in modules for extensibility. Apache is reliable, free, and relatively easy to configure.
Apache is free software distributed by the Apache Software Foundation. The Apache Software Foundation promotes various free and open source advanced Web technologies.
Often referred to as simply Apache, a public-domain open source Web server developed by a loosely-knit group of programmers. The first version of Apache, based on theNCSA httpd Web server, was developed in 1995.
In Short Apache:
• is a powerful, flexible, HTTP/1.1 compliant web server

• implements the latest protocols, including HTTP/1.1 (RFC2616)

• is highly configurable and extensible with third-party modules

• can be customized by writing 'modules' using the Apache module API

• provides full source code and comes with an unrestrictive license

• runs on Windows NT/9x, Netware 5.x and above, OS/2, and most versions of Unix, as well as several other operating system

Introduction to Web Technology
World Wide Web & Internet
Internet
A global network connecting millions of computers, cooperating with each other to exchange data using a common software standard. Through telephone wires and satellite links, Internet users can share information in a variety of forms.
World Wide Web
The World Wide Web (commonly abbreviated as "the Web") is a system of interlinked hypertext documents accessed via the Internet With a Web browser, one can view Web pages that may contain text, images, videos, and other multimedia and navigate between them using hyperlinks
The best-known client-server system in use today is the World Wide Web, commonly called just the Web. The basic client-server features are all there: a protocol called theHyperText Transfer Protocol (HTTP) is used for communications between a web server and a web client, the latter usually being represented by a web browserprogram running on a user's machine connected to the Internet.
WWW, web (computer network consisting of a collection of internet sites that offer text and graphics and sound and animation resources through the hypertext transfer protocol)
Note: The Web and the Internet are not the same thing. The Web is a collection of standard protocols, or instructions, sent back and forth over the Internet to gain access to information. The Internet, on the other hand, is a "network of networks" -- a more physical entity.

Introduction to Web Technology
Web Browsers
Short for Web browser, a software application used to locate and display Web pages. The two most popular browsers are Netscape Navigator and Microsoft Internet Explorer.
Both of these are graphical browsers, which mean that they can display graphics as well as text. In addition, most modern browsers can present multimedia information, including sound and video, though they require plug-ins for some formats.
A browser is an application program that provides a way to look at and interact with all the information on the World Wide Web. The word "browser" seems to have originated prior to the Web as a generic term for user interfaces that let you browse (navigate through and read) text files online.

Introduction to Web Technology
Web Standards (W3C)
Tim Berners-Lee founded the World Wide Web Consortium (W3C) at the Massachusetts Institute of Technology (MIT).
The mission of W3C is "To lead the World Wide Web to its full potential by developing protocols and guidelines that ensure long-term growth for the Web."
The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web (abbreviated WWW or W3). It is arranged as a consortium where member organizations maintain staff for the purpose of working together in the development of standards for the World Wide Web.
W3C was created to ensure compatibility and agreement among industry members in the adoption of new standards. Prior to its creation, incompatible versions of HTML were offered by different vendors, increasing the potential for inconsistency between web pages.
The consortium was created to get all those vendors to agree on a set of core principles and components which would be supported by everyone.

Introduction to Web Technology
Database Management System
Database Management System A DBMS can be thought of as a file manager that manages data in databases rather than files in file systems.
Four basic functions performed by all DBMS are:
• Create, modify, and delete data structures, e.g. tables

• Add, modify, and delete data

• Retrieve data selectively

• Generate reports based on data
• Database A collection of (usually) organized information or data in a regular structure, so   that it may be accessed with user friendly dialogs.

• Data refer to a collection of facts from which conclusions may be drawn. data is anything in   a form suitable for use with a computer .

• Data Model: A set of concepts to describe the structure of a database.Ex:
Types of Database Data Models
• flat file:Might be a basic phone list, where the database could consist of two fields: Name   and Phone Number.

• hierarchical is a data model in which the data is organized into a tree-like structure. The   structure allows repeating information using parent/child relationships:

• network Like the hierarchical model, this model uses pointers toward stored data.    However, it does not necessarily use a downward tree structure.

• relational All data is logically structured with in ‘relations’.

• The object model the data is stored in the form of objects, which are structures called   classes that display the data within. The fields are instances of these classes
Primary Key A primary key is one which uniquely identifies a row of a table. this key does   not allow null values and also does not allow duplicate values.

Unique key uniquely identify each row in a table. A unique key or primary key comprises a   single column or set of columns.

Candidate key A candidate key is a combination of attributes that can be uniquely used to   identify a database record without any extraneous data.

 Super key is a column or set of columns that uniquely identifies a row within a table.

Foreign key is a field in a relational table that matches the primary key column of   another table. The foreign key can be used to cross-reference tables.
TYPES OF RELATIONAL DATABASE
There are many Relational databases, some of them which is most used are namely:
Microsoft SQL Server is a relational database management system (RDBMS) produced by Microsoft. Its primary query languages are MS-SQL and T-SQL.
Microsoft Access is more suited for desktop use with a small number of users accessing it simultaneously.
MySQL is a relational database management system (RDBMS) based on SQL (Structured Query Language).
Oracle is best known for its sophisticated relational database products.
DBMS Languages D.B Language (Query) which will be necessary for relating data with the Database.
Query languages are computer languages used to make queries into databases and information systems.
Types of DBMS Languages
Data Definition Language (DDL) used to define the database structure or schema.

   Ex: CREATE, ALTER, DROP, TRUNCATE
Data Manipulation Language (DML) is used to retrieve, store, modify, delete, insert and update data in database.

   Ex: SELECT, INSERT, UPDATE, DELETE
Data Control Language (DCL) it is used to control access to database by securing it.Ex: GRANT, REVOKE
TCL (Transactional Control Language) It is used to manage different transactions occurring within a database.Ex: COMMIT, ROLLBACK
SQL COMMANDS
SQL SELECT Retrieves rows from a table or view
SELECT ColumnName1, ColumnName2, …

FROM Table1
SQL INSERT INTO clause facilitates the process of inserting data into a SQL table.
INSERT INTO table_name

VALUES (value1, value2, value3,...)
SQL WHERE clause works in conjunction with other SQL clauses like SELECT, INSERT and    UPDATE to specify a search condition for these statements.
SELECT ColumnName1, ColumnName2,

FROM Table1

WHERE search condition
• SQL DISTINCT clause works in conjunction with the SQL SELECT clause and selects only    distinct (unique) data from a database table(s).
SELECT DISTINCT Column1

FROM Table1
• SQL UPDATE Clause serves to update data in database table.
UPDATE Table1

SET Column1 = Value1, Column2 = Value2,…
SQL DELETE Clause is used to delete data from a database table.
DELETE FROM Table1
SQL TRUNCATE TABLE Clause deletes all rows from a database table.
TRUNCATE TABLE table name
SQL JOINS: SQL joins are used to query data from two or more tables, based on a relationship between certain columns in these tables.
Specifies four types of JOINs: INNER The INNER JOIN will select all rows from both tables as long as there is a match between the columns we are matching on.
OUTER This type of join returns all rows from one table and only those rows from a secondary table where the joined fields are equal (join condition is met).
LEFT The left outer join results in all the rows of the left collection, and where present, the rows of the right collection.
RIGHT The right outer join does exactly the same as the left outer join, but in reverse, the selected records will include all records of the second database table. One or more fields can serve as the join fields.

Server Side & Client Side Script
Introduction to HTML
HTML (Hypertext Markup Language) is the set of markup symbols or codes inserted in a file intended for display on a World Wide Web browser page. The markup tells the Web browser how to display a Web page's words and images for the user.
Each individual markup code is referred to as an element (but many people also refer to it as a tag). Some elements come in pairs that indicate when some display effect is to begin and when it is to end.
HTML pages are tag-based documents
• Don't look like documents they represent

• Really plain ASCII text files

• Most can be modified by attributes/values

• Tags usually appear in pairs

• Tags indicate how processing program should display text and graphics

• Processed by browsers “on the fly”

• Most have reasonable names or mnemonics
HTML TAGS HTML markup tags are usually called HTML tags
• HTML tags are keywords surrounded by angle brackets like <html>

• HTML tags normally come in pairs like <b> and </b>

• The first tag in a pair is the start tag, the second tag is the end tag

• Start and end tags are also called opening tags and closing tags.
Some HTML Tags example
START TAGEND TAG
• <HTML></HTML>
• <HEAD></HEAD>
• <TITLE></TITLE>
• <BODY></BODY>
• <H1>, <H2></H1>, </H2>, ...
• <IMG ...></IMG> (optional)
• <A ...></A ...>
• <P></P>
• <BR/>none; "empty" tag
• <OL></OL>
• <UL></UL>
• <LI></LI>
Basic Structure of HTML document
<html>
<head>
<title>Title bar text</title>
</head>
<body>
<p>Look, I'm a paragraph!</p>
</body>
	</html>
How To Name Your Document
Follow this format to name your document:
1.Choose a name. Anything. If you have a PC not running Windows 95, you are limited to eight letters, however.
2. Add a suffix. For all HTML documents, you will add either ".htm" or ".html".
(".htm" for PCs running Windows 3.x and ".html" for MAC and Windows 95/98 Machines)
Opening the Document in the Browser
1. Once you have your HTML document , you'll need to open it up in the browser. 1. Under the FILE menu at the very top left of this screen, you'll find OPEN, OPEN FILE, OPEN DOCUMENT, or words to that effect.
2. Click on it. Some browsers give you the dialogue box that allows you to find your document right away. Internet Explorer, and later versions of Netscape Navigator, require you to click on a BROWSE button or OPEN FILE button to get the dialogue box. When the dialogue box opens up, switch to the A:\ drive (or the floppy disc for MAC users) and open your document. If you saved the file to your hard drive, get it from there.
3. You might have to then click an OK button. The browser will do the rest.
Attributes and Values HTML elements known as attributes. This element can be used to set the text on your web page into different typefaces, sizes and colors. Most HTML tags can take attributes
Example:
<font face="times new roman" size="4" color="green">This text is using the 'times new roman' font face. It's relative size is '4' and the color is 'green'.</font>
img
Optional Attributes
AttributeValueDescriptionDTD
AcceptMIME_typeSpecifies the types of files that can be submitted through a file upload (only used with type="file")STF
Alignleft,right,top,middle,bottomDeprecated. Use styles instead. Specifies the alignment of an image input (only used with type="image")TF
AlttextSpecifies an alternate text for an image input (only used with type="image")STF
CheckedcheckedSpecifies that an input element should be preselected when the page loads (used with type="checkbox" or type="radio")STF
DisableddisabledSpecifies that an input element should be disabled when the page loadsSTF
MaxlengthnumberDefines the maximum length (in characters) of an input field (used with type="text" or type="password")STF
NamenameDefines a unique name for the input element.
Note: This attribute is required with type="button", type="checkbox", type="file", type="hidden", type="image", type="password", type="text", and type="radio"
STF
ReadonlyreadonlyIndicates that the value of this field cannot be modified (used with type="text" or type="password")STF
SizenumberDefines the size of the input element (cannot be used with type="hidden")STF
SrcURLDefines the URL of the image to display (only used with type="image")STF
TypeButton, checkbox, file, hidden, image, password, radio, reset, submit, textIndicates the type of the input element. The default value is "text"STF
valuevalueFor buttons, reset buttons and submit buttons: Defines the text on the button.

For image buttons: Defines the symbolic result of the field passed to a script.

For checkboxes and radio buttons: Defines the result of the input element when clicked. The result is sent to the form's action URL.

For hidden, password, and text fields: Defines the default value of the element.

Note: Cannot be used with type="file"
Note: This attribute is required with type="checkbox" and type="radio"
Forms
• HTML Forms are used to select different kinds of user input.

• A form is an area that can contain form elements.

• A simple HTML form with two input fields and one submit button

• Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form.
A form is defined with the <form> tag.
<form action="form_action.html" method="get">
  First name: <input type="text" name="fname" /><br />
  Last name: <input type="text" name="lname" /><br />
  <input type="submit" value="Submit" />
</form>
• type - Determines what kind of input field it will be. Possible choices are text, submit, and password.

• name - Assigns a name to the given field so that you may reference it later.

• size - Sets the horizontal width of the field. The unit of measurement is in blank spaces.

• maxlength - Dictates the maximum number of characters that can be entered.

• form action- Specifies the URL to send the data to. We will be sending our.

• method - We will only be using the post functionality of method, which sends the data without displaying any of the information to the visitor.

Server Side & Client Side Script
Introduction to CSS
It is time to take your web designing skills to the next level with Cascading Style Sheets (CSS). It is a way to control the look and feel of your HTML documents in an organized and efficient manner. With CSS you will be able to:
• Add new looks /styles to your old HTML

• Completely restyle a web site with only a few changes to your CSS code

• Use the "style" you create on any webpage you wish!
A stylesheet can, and should be, completely separate from your HTML documents. When you have mastered CSS and HTML, you will be able to separate your web site's design and formatting (CSS) from the content (HTML).
Types/Ways to attach CSS to HTML Documents.
Inline style sheet (inside (X)HTML element)
Internal/Embeded (inside the <head> tag)
External style sheet
The CSS syntax is made up of three parts: a selector, a property and a value:
selector {property: value}
Selectors :
First things you learn about when you start out with CSS are selectors. Selectors are obviously a fundamental part of CSS, but few developers use them to their full potential. While you can get a lot done with just the type, ID, and class selectors, there are many more. property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon, and surrounded by curly braces:
There are three types of selectors normally used namely:
1.class selector
2. id selector
3. # selector
class selector : The class selector is represented by a full-stop, “.”,and targets elements based on the value of their class attribute.
Syntax:
.[Class Name] { [Declaration Block] }
Example: 

.txt{font-family:Arial, Helvetica, sans-serif; font-weight:bold; font-size:24px;}

class name
Selector Declaration Block
id selector / # selector :

These are individually created for a particular use of an element. They can only be used once on a page, to uniquely identify a particular element. An ID selector is prefixed by the hash character "#".
For example, an ID selector could be:

#any{width:200px; height:200px; background-color:#00CC00;}

Or ex: #footer { font-size: 85% }

This would be coded in the HTML by using the ID attribute:


<p id="footer">XYZ</p>
Html selector : 

Html selectors are those which are attach with html tags and active on a applying that particular html tag.
Syntax: 

html tag symbol {[Declaration Block]}
Example: 

h1{font-size:10px; color:#FFFFFF; border:1px solid #FFFF00;}

body{background-color:#003366; color:#FFFFFF;}
Note: If the value is multiple words, put quotes around the value:
Inline style We add the styles within our HTML tags. This gets highest priority than Internal and external defined styles.
Example:Let us try to add a background style to one h1 tag.
<p style="color: #ff0000;">Some red text</p>
*Note: The inline css will apply in the HTML tags.
Internal /Imbeded Style This way you are simply placing the CSS code within the <head></head> tags of each (X)HTML file you want to style with the CSS.
Syntax:
<head>
<title><title>
<style type="text/css">
CSS Content Goes Here
</style>
</head>
<body>
With this method each (X)HTML file contains the CSS code needed to style the page. Meaning that any changes you want to make to one page, will have to be made to all. This method can be good if you need to style only one page, or if you want different pages to have varying styles.
How to Write an Internal Style Sheet
1. Open an HTML document in your Web editor.

2. Add the following inside the <head> element: <style type="text/css" media="all">

3. Be sure to add an HTML comment after the tag to protect older browsers: <!--

4. On a new line, start writing your CSS properties in the standard format: selector { style: property; }

5. When you've got all your styles included, close the comment: -->

6. And then close the style tag: </style>
A complete internal style sheet would look like this:
<style type="text/css" media="all">
<!--
p { font: 1em Times serif; color: #c00; }
h1 { font: 2em Times serif; color: #f00; }
-->
</style>
External Style sheets :
These styles are kept separately and called or linked from the required page. This is the syntax followed for linking a external style sheet.
<link rel="stylesheet" href="images/style.css" type="text/css">
The above tag is to be placed within the head tags of the page. We can keep our style details inside the file named style.css. Watch the linking of the file. The path details are to be given for including the style sheet.
Basic CSS Rule :
• Rules have two basic parts: selector and declaration

• Declaration also has two parts: property and value

• Selector tells the rule what to modify

• Declaration tells the rule how to modify it.

Server Side & Client Side Script
Introduction to Java Script
JavaScript is not JAVA. JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more.
JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, and Opera.
JavaScript is a "block" type language. It views commands as separate blocks of information, binds them together, then executes them. Some examples of these blocks are document, window, src, write, and status.
Remember:
• JavaScript is also CaSe SeNsItIvE.

• JavaScript is a client-side language, which means all the action occurs on the client's (reader's) side of things. This means that no trips to the server are required for.

• Adding JavaScript to your code allows you to change how the document looks completely, from changing text, to changing colours, to changing the options available in a drop-down list (and much, much more!).
What can a JavaScript Do?
• JavaScript gives HTML designers a programming

• JavaScript can put dynamic text into an HTML page

• JavaScript can react to events

• JavaScript can read and write HTML elements

• JavaScript can be used to validate input data

• JavaScript can be used to detect the visitor's browser

• JavaScript can be used to create cookies
Types of javascript
JavaScript comes in 2 varieties :
• Auto script Script that carries out a set of codes (known as a blocks) automatically without the need for visitor input or occurance.

• Trigger script Script that requires some visitor input or occurance to carry out a set of codes.
Method for implementation
So how are we going to get our JavaScript into our pages? JavaScript is written in the same way as HTML — in a text-editor. JS implementation is quite similar to CSS; you can link to outside files (with the file extension .js), or write blocks of code right into your HTML documents with the <script> tag. The usual choosing criteria apply — if you're using the same script on many pages, link to an external file; otherwise embed.
Implementation of javascript
The HTML <script> </script>tag is used to insert a JavaScript into an HTML page.
<html>
<body>
<script type="text/javascript">
document.write("Hello eBIZ!");
</script>
</body>
</html>
The code above will produce this output on an HTML page:
Hello eBIZ!
• To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language.

• So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends.

• The word document.write is a standard JavaScript command for writing output to a page.

• By entering the document.write command between the <script> and </script> tags, the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello eBIZ! to the page.
Note: If we had not entered the <script> tag, the browser would have treated the document.write("Hello World!") command as pure text, and just write the entire line on the page.
Where to Put the JavaScript
JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.
 Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.
<html>
<head>
<script type="text/javascript">
document.write("Hello eBIZ!");
</script>
</head>
</html>
• Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("Hello eBIZ!");
</script>
</body>
</html>
Using an External JavaScript
Sometimes you might want to run the same JavaScript on several pages, without having to write the same script on every page.
To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension.
Note: The external script cannot contain the <script> tag!
To use the external script, point to the .js file in the "src" attribute of the <script> tag:
<html>
<head>
<script type="text/javascript" src="validation.js"></script>
</head>
<body>
</body>
Standard Tips
• Javascript lines end with a semicolon. You may have noticed from the example on the previous page that javascript lines end with a semicolon.

• Always put the text within " ". When entering text to be handled by javascript, you should always put the text within " ".

If you forget to enclose your text in " ", javascript will interpret your text as being variables rather than text.

• Capital letters are different from lowercase letters. You should always remember that capital letters are different from lowercase letters.
JavaScript Variable
You create a variable with or without the var statement

var strname = some value
strname = some value

• When you declare a variable within a function, the variable can only be accessed within that function

• If you declare a variable outside a function, all the functions on your page can access it

• The lifetime of these variables starts when they are declared, and ends when the page is closed
JavaScript Popup Boxes
Alert box

• User will have to click "OK" to proceed

alert("sometext")

Confirm box

• User will have to click either "OK" or "Cancel" to proceed

confirm("sometext")

Prompt box

• User will have to click either "OK" or "Cancel" to proceed after entering an input value

prompt("sometext","defaultvalue")
JavaScript Language
• Conditional statement

if, if.. else, switch

• Loop

for loop, while loop

• try...catch

• throw
JavaScript Funcitons
• A JavaScript function contains some code that will be executed only by an event or by a call to that function

To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function

• You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file).

• Functions are defined either <head> or <body> section

As a convention, they are typically defined in the <head> Section.
Example: JavaScript Function
<html>
<head>
<script type="text/javascript">
// If alert("Hello world!!") below had not been written within a
// function, it would have been executed as soon as the page was loaded.
function displaymessage() {
alert("Hello World!")
}
</script>
</head>
<body>

<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>
Events & Event Handlers
Every element on a web page has certain events which can trigger invocation of event handlers

• Attributes are inserted into HTML tags to define events and event handlers
• Examples of events
> A mouse click

> A web page or an image loading

> Mousing over a hot spot on the web page

> Selecting an input box in an HTML form

> Submitting an HTML form

> A keystroke
Events
• onabort - Loading of an image is interrupted

• onblur - An element loses focus

• onchange - The content of a field changes

• onclick - Mouse clicks an object

• ondblclick - Mouse double-clicks an object

• onerror - An error occurs when loading a document or an image

• onfocus - An element gets focus

• onkeydown - A keyboard key is pressed

• onmouseover - The mouse is moved over an element

• onsubmit - The submit button is clicked

• onreset - The reset button is clicked
onFocus, onBlur and onChange
• The onFocus, onBlur and onChange events are often used in combination with validation of form fields.

• Example: The checkEmail() function will be called whenever the user changes the content of the field:

<input type="text" size="30"
id="email" onchange="checkEmail()">;
Example & Demo: onblur
<html>
<head>
<script type="text/javascript">
function upperCase() {
var x=document.getElementById("fname").value
document.getElementById("fname").value=x.toUpperCase()

</script>
</head>
<body>
Enter your name:
<input type="text" id="fname" onblur="upperCase()">
</body>
</html>
onSubmit
• The onSubmit event is used to validate ALL form fields before submitting it.

• Example:

The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled.

The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:

<form method="post" action="xxx.html" onsubmit="return checkForm()">
Example & Demo: onSubmit
<html>
<head>
<script type="text/javascript">
function validate() {
// return true or false based on validation logic
}
</script>
</head>
<body>
<form action="tryjs_submitpage.htm" onsubmit="return validate()">
Name (max 10 chararcters): <input type="text" id="fname" size="20"><br />
Age (from 1 to 100): <input type="text" id="age" size="20"><br />
E-mail: <input type="text" id="email" size="20"><br />
<br />
<input type="submit" value="Submit">
</form>
</body>
</html>
JavaScript Object
• JavaScript is an Object Oriented Programming (OOP) language

• A JavaScript object has properties and methods
Example:

String JavaScript object has length property and toUpperCase() method
<script type="text/javascript">
document.write(txt.length)
var txt="Hello World!"
document.write(txt.toUpperCase())
</script>

Server Side & Client Side Script
Introduction to PHP
PHP is short for PHP Hypertext Preprocessor. What it does is to process hypertext (i.e., HTML web pages) before they leave the web server. This allows you to add dynamic content to pages while at the same time making that content available to users with all types of browsers. PHP is an interpreted programming language, like Perl.
PHP is server-side:
Your browser doesn't realise the pages it is viewing are initially written with PHP. All it receives is an HTML page - as complex or as simple as you want.
PHP is HTML-embedded:
A PHP page can be simply an HTML page with a little PHP sprinkled here and there (we'll see how).

The PHP bits are parsed ("translated") by the server - in the examples presented here, they will be mainly used to produce more HTML code. The HTML code on the page is sent directly to the browser.
PHP has similarities with other programming languages:
C and Perl are two of them. In my case, learning a bit of Perl really helped me get started and understand what PHP could do for me - and how it worked.
Points to be Remember
Here is a little information about what matters and what doesn't when writing PHP.
. Whitespace (tabs, spaces, returns) doesn't really matter. You can write : <?$title="mytitle";?> or <? $title = "mytitle" ; ?>, both work.

. Each statement ends with a semi-colon ";".
. When inside PHP tags, you can add comments:

o /* comment */
o # comment
o // comment
(everything until the end of the line will be ignored in the two last cases; in the first case, the comment can span multiple lines).
. You can switch from PHP to HTML and back just about anywhere. Make your experiences!

. PHP files are usually named "something.php" (on some servers you can use "something.php3" or even "something.phtml").
Language Syntax
To add PHP code to a web page, you need to enclose it in one of the following special sets of tags:
<? php_code_here ?>

OR

<?php php_code_here ?>

OR

<script language="php">
php_code_here
</script>
Example:
So, what kind of code goes where it says php_code_here? Here's a quick example.
<html>
<head>
<title>My Simple Page</title>
</head>
<body>

<?php echo "Hello eBiz!"; ?>
</body>
</html>
If you copy that code to a text editor and then view it from a web site that has PHP enabled you get a page that says Hello eBiz!
*echo helps you to display any combination of string and variables on your page
If you wish to see all your PHP system information and configuration details, add the following line to the PHP file you created above:
<html>
<head>
<title>My Simple Page</title>
</head>
<body>
<?php phpinfo(); ?>
</body>
</html>
Variables
Variables are your friends, whenever you have something to store somewhere temporarily give it to the variables and they will keep it for you and whenever you need it call related variables and they will give it to you and you can change, add or delete the received information and return the new values to variables..
To declare a variable in PHP, just place a $ character before an alpha-numeric string, type an equals sign after it, and then a value.
<?php $myvar = "Hello eBiz"; ?>
The above code sets the variable $myvar to a value of "Hello eBiz ".
We can now use that variable to replace text throughout the page, as in the example below:
<html>
<head>
<title>My Simple Page</title>
</head>
<body>

<?php $myvar = "Hello eBiz ";
echo $myvar; ?>
</body>
</html>
The above code creates a page that prints the words "Hello eBiz ". One reason to use variables is that you can set up a page that repeats a value throughout and then only need to change the variable value to make all the values on the page change.
String is a type in PHP and it is a series of characters.
1.	<?php
2.	   $str_1 = 'I am a ebizer';
3.	   $str_2 = 'and I am a php developer';
4.	   echo $str_1;
5.	   echo $str_2;
6.	?>
PHP Operators
Operators are used to operate on values.
Sometimes while working with strings in our code, we need to join two strings. In PHP, you can use '.' to concatenate two or more strings together to form a single string.
Example 1 - Concatenating PHP Strings
<?php
$str1 = "I Love PHP.";
$str2 = "PHP is fun to learn.";
echo $str1." ".$str2;
?>
Result:
I Love PHP. PHP is fun to learn.
Assignment Operators
The basic assignment operator in PHP is "=". This means that the operand to the left of "=" gets set to the value to the right of "=".
Arithmetic Operators
img
Combined Operators
You can combine an arithmetic operator with the assignment operator to form a combined operator. Combined operators are shown below:
img
Comparison Operators
img
Logical Operators
img
Php Functions
The real power of PHP comes from its functions.
In PHP - there are more than 700 built-in functions available.
A function is a block of code that can be executed whenever we need it.
Creating PHP functions:
. All functions start with the word "function()"

. Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number)

. Add a "{" - The function code starts after the opening curly brace

. Insert the function code

. Add a "}" - The function is finished by a closing curly brace
The syntax to create a user defined function is:
function function_name(){ 
//statements here
}
Using Your PHP Function
<?php
function my_function(){
    echo " We deliver quality, not quantity!<br />";
}
echo "Welcome to ebizelindia.com <br />";
my_function ();
echo "Thanks for reading our product! <br />";
echo " remember... <br />";
my_function ();
?>
Result
Welcome to ebizelindia.com
We deliver quantity, not quality!
Thanks for reading our product! 
and remember... 
We deliver quality not quantity!
Includes
The include() function takes all the text in a specified file and copies it into the file that uses the include function.
INCLUDE is used to append the code from an external file into the current file. The syntax for INCLUDE is
include ("external_file_name");
This is a convenient feature for a large website. Often, we may want to change an element of the website that is consistent across the entire site, yet we don't want to go through the trouble of updating every single file. In this case, we can simply use INCLUDE in every file to call the same external file, and then all we need to change is the content in that one external file.
Let's look at a simple example. Assuming we have the following two files:
index.php
<?php 
  print "This is the original content<br>"; 
  include ("external_file"); 
?>
external_file
<?php 
  print "This is the external content"; 
?>
Upon executing index.php, we'll get the following output:
This is the original content

This is the external content
require
. The two constructs are identical in every way except how they handle failure.

. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).
Syntax:
require(path_to_file);

require path_to_file;
Include_once and require_once
Include_once and require_once can be used just like include and require respectively.The difference is that if the included file has already been included by earlier code, it will not be re-included.
Quick Form Let's face it; forms are the cornerstone of almost all web interactivity. As such, let's explore some very basic form processing with PHP to get the hang of it.
First you create the HTML form and call it form.php
<html> 
<head></head> 
<body> 
<form action="myfirstform.php" method="get"> 
Enter your comments:
Name: <input type="text" name="name" />
Age:  <input type="text" name="age" />
<input type="submit" value="Send">
</form> 
</body> 
</html>
If you are familiar with writing CGI to process your forms, you can see that the HTML side is almost identical with the <form action=" myfirstform.php" method="post"> being the critical piece. When a user hits the "Send" button, it calls the .php file entitled form_process.php. This is the file that will be able to capture the input the user entered into the form and "do" something with it (e-mail, display on a page, etc.).
PHP $_GET
The $_GET variable is used to collect values from a form with method="get".
The $_GET variable is used to collect values from 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 it has limits on the amount of information to send (max. 100 characters).
Example:
The " myfirstform.php " file can now use the $_GET variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_GET array):
Welcome <?php echo $_GET["name"]; ?>.<br />

You are <?php echo $_GET["age"]; ?> years old!
Why use $_GET?
Note: When using the $_GET variable all variable names and values are displayed in the URL. So this method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
Note: The HTTP GET method is not suitable on large variable values; the value cannot exceed 100 characters.
$_POST
The $_POST variable is an array of variable names and values sent by the HTTP POST method.
<form action=" myfirstform.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>
The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the names of the form fields will automatically be the ID keys in the $_POST array):
Welcome <?php echo $_POST["name"]; ?>.<br />

You are <?php echo $_POST["age"]; ?> years old!
$_REQUEST
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
PHP LOOPING
Another very important idea in programming is the concept of looping or iteration. This is the repetition of specific pieces of code for a specified number of times. This can be incredibly useful if we want to write a list of data from a database to the screen, or if we need to iterate through a large bunch of data and do something with it.
Looping statements in PHP are used to execute the same block of code a specified number of times.
There are many types of loops in PHP and they are common to other programming languages.
session
. However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.

. A session is a way to store information (in the form of variables) to be used across multiple pages.

. Unlike a cookie, specific variable information is not stored on the users computer.

. It is also unlike other variables in the sense that we are not passing them individually to each new page, but instead retrieving them from the session we open at beginning of each page.
Example:Call this code to login..php
<?php 
// this starts the session 
session_start(); 

// this sets variables in the session 
$user=$_SESSION['name'];
?>
Remember
When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
Cookie
A cookie is a flat file that stores tiny bits of information. It is stored on the client's machine and is passed to the client when they visit your site. Each cookie can store anything from usernames to number of visits to a site.
Create a Cookie using PHP
Cookies are created using the setcookie() function. Below is an example of the setcookie() function
setcookie($name, $value, $expired, $path, $domain, $secure)
These are the values that you can pass into the setcookie() function.
The values are: name of the cookie, value of the cookie, the date the cookie expires, path where the cookie is available on the server, domain where the cookie is available, and where it is coming from a secure page.
The three values that we are worried about are $name, $value, and $expired.
Below is the php code to create a php cookie named "username". We set the value of the cookie to "Tom", and set the expiration date at one hour from now.
<?php
setcookie("username", "kamal", time()+3600);
?>
Retrieve & Display a Cookie using PHP
<?php
echo $_COOKIE["username"];
?>
Delete a cookie using PHP . Cookies are deleted by simply setting the expiration date to a past date.
PHP File Upload
With PHP, it is possible to upload files to the server. A very useful aspect of PHP is its ability to manage file uploads to your server.
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">select Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
On line one we tell the form to send the information to our PHP file (which we will create later) named upload.php, we then tell the form to send the information as "multipart/form-data", this is required to send files through the form. Then we create an input with type="file", this makes an input with the required buttons to select a file. Finally we add a button to submit the form.
PHP, uploaded files are accessed via the $_FILES array:
. $_FILES["file"]["name"]: The original filename on the client's machine.

. $_FILES['file']['type']: The mime type of the file.

. $_FILES['file']['size']: The size, in bytes, of the uploaded file.

. $_FILES['file']['tmp_name']: The temporary filename of the file in which the uploaded file was stored on the server.
Email messaging
PHP offers the possibility to send email in a simple easy way, to that end the language provides us with the statement mail().
<?php mail(receiver, subject, message text); ?>
receiver parameter we will write the email address where the message will be sent to; in the parameter subject, the message subject; and in the parameter message text, the message body in plain text format.
There is an extended syntax of the mail() statement that allows us to include additional information to the header of the message.
<?php 
   mail(receiver, subject, message text, additional parameters);    
?>
Example
<?php
//Check whether the submission is made
if(isset($hidSubmit)){
//Declarate the necessary variables
$mail_to=$txtEmailto;
$mail_from=$txtEmailfrm;
$mail_sub=$txtSub;
$mail_mesg=$txtMsg;
//Check for success/failure of delivery 
if(mail($mail_to,$mail_sub,$mail_mesg,"From:$mail_from/r/nReply-to:$mail_from"))
echo "<span class='red'>E-mail has been
 sent successfully from $mail_sub to $mail_to</span>";
else
echo "<span class='red'>Failed to send the 
E-mail from $mail_sub to $mail_to</span>";
}
?>
This is all about the short description of php with covering all the basic necessary points which can be mostly used in a development project.rest
For full detail please visit our site http://education.ebizelindia.com.

Server Side & Client Side Script
OOPS CONCEPT
This is a technique used to create programs around the real world entities. In OOPs programming model, programs are developed around objects and data rather than actions and logics. In OOPs, every real life object has properties and behavior.
CLASS "class" as sort of a template for data. The most common definition states that a class is a template for an object.
• Every class definition begins with the keyword class, followed by a class name, which can be any name that isn’t a reserved word in PHP.

• Followed by a pair of curly braces, which contains the definition of the classes members and methods.

• A pseudo-variable, $this is available when a method is called from within an object context.

• $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object).
Explain the term : The most common definition states that a class is a template for an object. Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template.
Example:
class  car {

	      }
Object
Object is the basic entity of object oriented programming language . Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (variables) and uses the behavior (methods) defined in the class.
EX: Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).
An instance is an executable copy of a class. Another name for instance is object.
Explained the term:
A pattern (exemplar) of a class. The class of car defines all possible cars by listing the characteristics and behaviors they can have; the object maruti 800is one particular car, with particular versions of the characteristics. A car have all some models; maruti has 800 model.
NEW
To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error.
•Classes should be defined before instantiation (and in some cases this is a requirement).
Example:
<?php
$objectcar = new car();
?>
In the class context, it is possible to create a new object by new self and new parent.
• When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned.
• This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.
• Here $objectcar is a new object

• New is the initialization operator

• And the meaning of whole of the line describes that an instance of name objectcar of type car is initialized.
Variables: Variables are places in memory to store values. Every language offers slightly different characteristics.
Declaring a variable To use variables, you must notify the compiler of the name and the type of the variable (declare the variable).
The syntax for declaring a variable in Java is to precede the name of the variable with the name of the type of the variable as shown below. It is also possible (but not required) to initialize a variable in Java when it is declared as shown.
int var1, var2 = '0';
Functions: A Functions is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name.

A function is a block of code that can be executed whenever we need it.
class car {
	public $name;
 
	public function myfunction($name) {
		$this->name = $name;
	   }
Specifiers: Access specifiers specify the level of access that the outside world (i.e. other class objects, external functions and global level code) have on the class methods and class data members. Access specifiers can either be public, private or protected.
Access specifiers are used as a key component of Encapsulation and Data Hiding. By using either of the access specifiers mentioned above i.e. public, private or protected you can hide or show the internals of your class to the outside world.
Public
A public access specifier provides the least protection to the internal data members and member functions. A public access specifier allows the outside world to access/modify the data members directly unlike the private access specifier. Look at the example below:
class car {
	public $name;
 
	public function myfunction($name) {
		$this->name = $name;
	   }
Private
A private access specifier is used to hide the data member or member function to the outside world. This means that only the class that defines such data member and member functions have access them. Look at the example below:
Explained
class Customer {
	private $name;
 
	public function setName($myname) {
		$this-> myname = $ myname;
	}
 
	public function getName() {
		return $this-> myname;
	}
}
 
$c = new Customer();
$c->setName("Devesh Chauhan");
echo $c-> myname; //error, $name cannot be accessed from outside the class
               //$name can only be accessed from within the class
 
echo $c->getName(); //this works, as the methods of the      class have access
                    //to the private data members or methods
Protected: A protected access specifier is mainly used with inheritance. A data member or member function declared as protected will be accessed by its class and its base class but not from the outside world (i.e. rest of the script).
We can also say that a protected data member is public for the class that declares it and it’s child class; but is private for the rest of the program (outside world). Look at the example below:
Some OOPS Definitions
Encapsulation:Encapsulation is the mechanism that binds together code and the data it manipulates
Inheritance: Inheritance is nothing but , inherit the properties of an another object
Polymorphism: In general words, a compound or a substance having different forms,likewise a method behaving differently on different calls,here we have method overloading and method overriding.
Three distinct forms of polymorphism
From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
• Method overloading

• Method overriding through inheritance
Method overloading
I covered method overloading as one form of polymorphism (compile-time polymorphism) in a previous lesson. I also explained automatic type conversion and the use of the cast operator for type conversion in a previous lesson.
Method overriding and class inheritance
I discussed runtime polymorphism implemented through method overriding and class inheritance in more than one previous lesson.
Encapsulation, Inheritance and Polymorphism are main pillars of OOPs.

Server Side & Client Side Script
Introduction to MySQL
Pronounced "my ess cue el" (each letter separately) and not "my SEE kwill."MySQL is a database system. A database is really just a method of storing lots of data in an efficient manner, and a way of extracting that data as well. MySQL uses, naturally enough, SQL, or Structured Query Language, to do its data extraction.
What is Database: A database is a collection of information that is organized so that it can easily be accessed, managed, and updated.A computer database relies upon software to organize the storage of data. A collection of (usually) organized information in a regular structure.
Query: We define a query in the form of a scalar variable then call upon that variable using our connection script and the query function.
MySQL databases are queried using a subset of the standard Structured Query Language (SQL) commands.
Background information
MySQL is a relational database system capable of storing multiple databases. Each database contains tables that store data. MySQL is a quick, robust, and cost effective database solution. Queries are performed on the database to insert, update, or delete data. Like PHP and many other languages MySQL queries are delimited with a semicolon.
Milestones in MySQL development include:
• MySQL was first released internally on 23 May 1995
Windows version was released on 8 January 1998 for Windows 95 and NT
Why we use a Database
Databases are most useful when it comes to storing information that fits into logical categories. For example, say that you wanted to store information of all the employees in a company. With a database you can group different parts of your business into separate tables to help store your information logically. Example tables might be: Employees, Supervisors, and Customers. Each table would then contain columns specific to these three areas. To help store information related to each employee, the Employees table might have the following columns: Hire, Date, Position, Age, and Salary.
We have learned the sql in DATABASE Manual and the one thing I letto know you that the basic concepts and fundamental are the same , so without wasting our rpoints here we interact you with the mysql in practicall manner, so that the lagic, you have learn in DATABASE Manuall is very cleared to you.
Although you can set up MySQL manually on your home PC, it can be rather difficult for a beginner to do, and would require more than a few lessons!
We here discuss steep by step the concept of mysql, so that it will be ease to learn you.
General information
First of all you can create a database,If you install WAMP server then it can all do with mouse , as all the options required with mysql database is available on mouse click, but our concern to learn mysql concept,not the specific tool , so here we describe all the commands and example by doing it manually.
Let’s Start with Our Process
Step 1. Creating a Database
First of all we create a Database.
To create a new database:
CREATE DATABASE dbstudent ;
CREATE DATABASE is the command for creating the Database, and dbstudent is the name of the database.
So without wasting the time we create a database of name student
Step 2. Connecting the Mysql Databaserver
Opening a connection to MySQL database from PHP is easy. Just use the mysql_connect() function like this.
img
$dbhost : Name of MySQL server. When your webserver is on the same machine with the MySQL server you can use localhost as the value of $dbhost.

$dbuser and $dbpass : valid MySQL user name and password.
• Don't forget to select a database using mysql_select_db() after connecting to mysql. If no database selected your query to select or update a table will not work.
• Sometimes a web host will require you to specify the MySQL server name and port number. For example if the MySQL server name is db.php-mysql-tutorial.com and the port number is 3306 (the default port number for MySQL) then you you can modify the above code to .
<?php
$dbhost = 'db.php-mysql-tutorial.com:3306';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser,
 $dbpass) or die              
        ('Error connecting to mysql');

$dbname = dbstudent;
mysql_select_db($dbname);
?> 
Note: It's a common practice to place the routine of opening a database connection in a separate file. Then everytime you want to open a connection just include the file. Usually the host, user, password and database name are also separated in a configuration file.
An example of config.php that stores the connection configuration and opendb.php that opens the connection are :
<?php
// This is an example of config.php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = dbstudent;
?> 
 <?php
// This is an example opendb.php
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
 or die              
        ('Error connecting to mysql');
mysql_select_db($dbname);
?> 
So now you can open a connection to mysql like this :
// This is your php page including 
the connection and configuration files.
<?php
include 'config.php';
include 'opendb.php';
// ... do something like insert or select, etc

?> 
Closing the connection
The connection opened in a script will be closed as soon as the execution of the script ends. But it's better if you close it explicitly by calling mysql_close() function. You could also put this function call in a file named closedb.php.
<?php
// an example of closedb.php
// it does nothing but closing
// a mysql database connection
mysql_close($conn);
?>
Now that you have put the database configuration, opening and closing routines in separate files your PHP script that uses mysql would look something like this :
<?php
include 'config.php';
include 'opendb.php';
// ... do something like insert or select, etc
include 'closedb.php';
?> 
Step4.Create a Table
A database is organized into tables, and each table is organized into columns and rows, also called fields and entries, respectively. So, a theoretical database might look like this:
img
And so on. Due to this organization, you can ask very specific queries, like: "give me all the entries in the 'faculty' table whose last name starts with 'm'." That's what we'll be learning.
So our main concern to create a table first
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,
....
)
Note:
As you see the table above you notice that: Each row holds an id, which is the primary key, the name of the student, and email . As you know about the primary key , this is the key through which we have fire a query in a specified row.This is unique throughout the table,and never be null.
CREATE TABLE students (
       stu_Id int unsigned not null auto_increment,
       first_Name varchar(25) not null,
       last_Name char(30) not null,
	email char(20) not null,
       primary key(stu_Id));
This is what the basic mysql statement for creating a table of name students with first_name, last_name, email, and stu_Id,with stu_Id is assigning primary key.
Some commonly used data types
 CHAR(length) - fixed length character string

 VARCHAR(length) - variable length character string with max length length.

TEXT - variable length character string with max length of 64KB of text.

INT(length) - 32-bit integer with max length digits (the '-' is counted as a 'digit' for a negative number.)

DECIMAL(length,dec) - Decimal number up to total length display characters. The dec field indicates the maximum number of decimal places allowed.

 DATE - Date value (year, month, date))

TIME - Time value (hours, minutes, seconds)

ENUM("value1","value2", ....) - List of enumerated values.
Some optional parameters:
NOT NULL - A value must be provided. The field cannot be left blank.

DEFAULT default-value - If no value is given, the default-value is assigned to the field.
To create tables in the new database you need to do the same thing as creating the database. First create the SQL query to create the tables then execute the query using mysql_query() function.
//Example: Submit.php
<?php
include 'config.php';  // Set Local variables
include 'opendb.php'; //connection open file
$query  = 'CREATE DATABASE ‘dbstudent ’;
$result = mysql_query($query);
	mysql_query() sends an unique query 
to the currently active database on the server
that's associated with the specified link_identifier.
mysql_select_db(' dbstudent ')or die('Unable to select database'); 
	This command select the database you created.

CREATE TABLE students (
       stu_Id int unsigned not null auto_increment,
       first_Name varchar(25) not null,
       last_Name char(30) not null,
	email char(20) not null,
       primary key(stu_Id));
$result = mysql_query($query);
$result = mysql_query($query);

include 'closedb.php';
?>
Remember
* mysql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.
* The mysql_query() function executes a query on a MySQL database.
*This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.
* In the above example mysql_query() was followed by die(). If the query fail the error message will be printed and the script's execution is terminated. Actually you can use die() with any function that might not execute properly. That way you can be sure that the script won't continue to run when an error occured.
Step 6. Creating query for inserting the data
Now you create a table , then the next step is to insert your data (Student information) in the table.
Syntax for inseting the Data
When data is put into a MySQL table it is referred to as inserting data. When inserting data it is important to remember the exact names and types of the table's columns.
INSERT INTO table_name ( field1, field2,...fieldN )
                       VALUES
                       ( value1, value2,...valueN );
Example:
Inserting data to MySQL is done by using mysql_query() to execute INSERT query. Note that the query string should not end with a semicolon. Below is an example of adding a new MySQL user by inserting a new row into table user in database mysql :
<?php
include 'library/config.php';
include 'library/opendb.php';
mysql_select_db($mysql);
$query = "INSERT INTO students 
(email, first_Name, last_Name, stu_Id VALUES
 (‘kamal @ebizel.com, ‘Kamal’ , 'Banoudhia', 1107)";

mysql_query($query) or die('Error, insert query failed');

$query = "FLUSH PRIVILEGES";
mysql_query($query) or die('Error, insert query failed');
include 'library/closedb.php';
?>
This is just a demo for the query we write above.
img
Now u Make a data base and inserts the value through query.

But besides from this there is many others query, which interacting the database with the following tables.
So we describe you some commom mysql queries:
The Select command is used to select the records from a table using its field names. To select all the fields in a table, '*' is used in the command. The result is assigned to a variable name as shown below:
Syntax:

$selectSQL=("SELECT field_names FROM tablename");

Example:

$selectSQL=("SELECT * FROM students");
DELETE Command
The Delete command is used to delete the records from a table using conditions as shown below:
Syntax:

$deleteSQL=("DELETE FROM tablename WHERE condition"); 

Example:

$deleteSQL=("DELETE FROM student WHERE stu_Id=1107");
UPDATE Command
There may be a requirement where existing data in a MySQL table need to be modified. You can do so by using SQL UPDATE command. This will modify any field value of any MySQL table.The Update command is used to update the field values using conditions. This is done using 'SET' and the fieldnames to assign new values to them.
Syntax:

$updateSQL=("UPDATE Tblname SET (fieldname1=value1,fieldname2=value2,...) WHERE fldstudid=IdNumber");

Example:

$updateSQL=("UPDATE students SET first_Name=Amit,last_Name=sheal WHERE stu_Id=1107");
Tips:
• You can update one or more field all together.

• You can specify any condition using WHERE clause.

• You can update values in a single table at a time.
MySQL Like Clause
We have seen SQL SELECT command to fetch data from MySQL table. We can also use a conditional clause called WHERE clause to select required records.
A WHERE clause with equal sign (=) works fine where we want to do an exact match. Like if "first_Name = 'Kamal'". But there may be a requirement where we want to filter out all the results where tutorial_author name should contain "ka" or it’s started with “K” or it is ended with “al”. This can be handled using SQL LIKE clause alongwith WHERE clause.
If SQL LIKE clause is used along with % characters then it will work like a meta character (*) in Unix while listing out all the files or directories at command prompt.
Without a % character LIKE clause is very similar to equal sign alongwith WHERE clause.
Syntax:

Here is generic SQL syntax of SELECT command along with LIKE clause to fetch data from MySQL table:

SELECT field1, field2,...fieldN table_name1, table_name2...
WHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'
• You can specify any condition using WHERE clause.

• You can use LIKE clause alongwith WHERE clause.

• You can use LIKE clause in place of equal sign.

• When LIKE is used alongwith % sign then it will work like a meta character search.

• You can specify more than one conditions using AND or OR operators.

• A WHERE...LIKE clause can be used alongwith DELETE or UPDATE SQL command also to specify a condition.
Example:
SELECT * from students
WHERE first_Name LIKE 'ka%';
Mysql_fetch_object()
First thing in your mind in what is mysqlfetch object and how it is work. where you insert the data in the table, then the main concern is how you fetch the specified data from the desired table and what is the exact function which makes the query fast. most of the student is confused about the function. we will give you the explanation.
Definition: Mysql_fetch_object returns the result from the database as objects, Fetches a result row as object.
mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array.
Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Difference between mysql_fetch_object and mysql_fetch_array
mysql_fetch_object : will return the results from database as objects. fields will be accessible like in objects i.e $result->name,$result->cust_name

mysql_fetch_array : will return the results from database as array. fields will be accessible like in objects i.e $result[name],$result[cust_name]
Example:
<?php 
mysql_connect (“hostname”,”user”,”password”);
mysql_select_db(“dbstudents”);

$SQL=mysql_query (“SELECT * FROM students” ) or   die(mysql_error());
;
While ( $row= mysql_fetch_object($SQL)){
		echo $row?first_Name ;
		echo $row?stu_Id ;
}
mysql_free_result($SQL); //will free the memory from the $sql 
?>
Result:
It will produce the result as:

Kamal 1007
mysql_fetch_array()
We discuss above the work of mysql_fetch_array,as you grasp the feathers of same, we describe The details of mysql_fetch_array so that it will be clear to you.
Definition: Fetches a row of data as an array from a MySQL result handle it Fetch a result row as an associative array, a numeric array, or both.
Return the current row with both associative and numeric indexes where each column can either be accessed by 0, 1, 2, etc., or the column name.
<?php 
$result = mysql_query (“SELECT * FROM students”) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo “first_Name”.”-“. “stu_Id”;
?>
Result:
Kamal -1107
mysql_fetch_row
Get a result row as an enumerated array.
<?php

$result = mysql_query  (“SELECT * FROM students”) or die(mysql_error());

$row = mysql_fetch_row ($result) or die (mysql_error());
Echo $row[0];
Echo $row[1];

?>
Result:
Kamal Banoudhia
mysql_num_rows()
Returns number of rows in result on success, or NULL on error.
mysql_num_rows () function retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERTUPDATEREPLACE orDELETE query, use mysql_affected_rows().
<?php 

$result = mysql_query ( “SELECT * FROM students") or die(mysql_error());

//returns number of rows in result
$row = mysql_num_rows( $result) or die( mysql_error());
//Print number of rows;
Echo “$row \n ”;
?> 
Result :
1 Row
explode()
function explode() is used to split a string into pieces. Cutting of the string depending upon a substring or a single character, and returns the chunked form of the string as an array.
<?php 
//For example we have a string
$names = “subh, kamal,aman,pradeep, saurabh”;

//now you want to make each name as element of array and access it individually.
//so what you do is ?

$arr = explode(",",$ names);
//means : we have made pieces of string $text based on seperator ','
//and put the resulting array in variable $arr
?>
so now $arr contains data as shown following..
By the way the following result can be generated by using print_r() fucntion, which prints out the actual structure of data cotnained in a variable.
So I used print_r($arr); and results are following…
Result:
Array(
[0] => subh
[1] => kamal
[2] => aman
[3] => pradeep
[4] => saurabh
)

which is equal to 

$arr = Array("subh "," kamal "," aman "," pradeep "," saurabh ");

implode()
function implode() is oppisite to the explode function. It rejoins any array elements and returns the resulting string, which may be put in a variable.
<?php 
$names = Array ("ajay","kashif","timsi","ishan","akash");

//and you wish to combine it in a string,
 by putting a seperator '/' between //each element of the array.
$row = implode(“,” , $row);
echo $row ;            //Result:ajay,kashif,timsi,ishan,akash
?>
split()
Split string into array by regular expression, SQL Split Function is use to SPLIT a sentences based on the Delimeter.
Delimeter is a string character used to identify substring limits. Delimiters may be slash, dot, or hyphen..
<?php
// Delimiters may be slash, dot, or hyphen
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?> 
Result: Month: 04; Day: 30; Year: 1973
Dabtabase backup
Your Mysql database may have many tables, and all the tables contains thousands of records, and these records may be very important to you, then what happens if your database may delete or corrupt or clean from the hard disk, due to some system crash or any physical damage .
So being a software developer it is good practice to take database backup properly.but it will also a problem, as u don’t know how to take a database backup. The exact procedure for taking database backup is as follows:
MySQL database backup can be accomplished in two ways:
Method-1#-Copying the MySQL database through command prompt:
Step1: Click on start (on the windows button)?then go to run option?type “cmd” (without commas)
Step2: Now You will see a command prompt window with “c:\documents and setting \ >”
Step3: Then you must have to set the path.
* Please follow this path very carefully because this is the main and tedious step.
You can go to inside of bin folder of mysql folder..
(Actually confusing point is, if you install wamp then first you see a bin folder in wamp folder then as u go to that folder you have see three folder as php, mysql and apache , and if you goto any of the three, they all have bin folder, so our main concern to go inside the mysql bin)
img
Step4: Now proceed from step 2

type “path” in the command prompt and set the path we have above :the complete command is:

path= C:\wamp\bin\mysql\mysql5.0.51b\bin ,, then press Enter
img
step5: Now as you press “Enter” you database backup will be done.
You can see your backup in the defined directory (by default it is on c:\documents and setting \any_folder) see the dir path on your command window, where your command prompt will make the dir .
Method2# Through making batch file
This is also a very easy process the main difference from the previous method is it write the “path” setting in the batch file and instead of giving command for path setting in command prompt , u can only give the name of that file.
*Note the batch file should be saved with .bat extension. So steps for methos 2 is as follow:
Step1: Click on start (on the windows button)?then go to run option?type “cmd” (without commas)
Step2: Now minimize the command prompt window go to c:/ and then write click to open a text file, write the path location as describe in the method 1ie bin path of mysql The path is path= C:\wamp\bin\mysql\mysql5.0.51b\bin
Step 3: And save the file as “name.bat”(must type the .bat extension so that you will get a batch file and remind it that saving the file with any name .bat covers with inverted commas ex-”text.bat”,”abc.bat” etc.
Step4: Now maximize your command prompt and type the name of your batch file,it will set the path describe in your file.
Then now follow the steps as commands mysql –uroot –p dbstudent > backupfile.sql

Then press enter.Finally you will get the backup file.

0 comments: