Movatterモバイル変換


[0]ホーム

URL:


Tushar Rajput, profile picture
Uploaded byTushar Rajput
DOCX, PDF4,045 views

PHP HTML CSS Notes

The document provides an overview of HTML (Hypertext Markup Language) including:1) HTML is a markup language used to describe web pages using tags to structure content like headings, paragraphs, lists, links, images and tables. 2) Various HTML tags are described like <h1>-<h6> for headings, <p> for paragraphs, <b> for bold, <i> for italic, and <a> for links. 3) Additional HTML concepts covered include internal and external CSS, meta tags, images, tables, frames, iframes and cascading style sheets (CSS) for styling content.

Embed presentation

Downloaded 93 times
1
2HTMLHTML is a not a scripting language or programming language.It is asimple markup language with the pair of markup tags.The first tag is known as opening tag (or) starting tag. The second tagis known as closing (or) end tag.HTML is used to describe the web pages.HTML can be written in notepad, notepad++, dream viewer, adov andcs5.HTML file can be saved with .html as its extension.The look end of an web page should be same on the all browsers. If itis not same the cross browser compatibility.Tags in html :Heading tags are h1, h2,h3,h4,h5,h6Ex: - <h1>welcome to html</h1>..<h6> welcome to html</h6><hr>: - this tag is used for horizontal line<br>: - this tag is used for break<p>: - this tag is used for paragraph content<b>: - this tag is used for bold content<i>: - this tag is used for italic content<link>: - this tag is used for connect the style sheets<script>: - this tag is used for JavaScript<big>: - this tag is used for big content
3<strong>: - this tag is used for strong content<blink>: - this tag is used for blink content<del>: - this tag is used for delete the content<strike>: - this tag is used for strike<u>: - this tag is used for underline content<ins>: - this tag is used for insert content<q>: - this tag is used for quotation content<sup>: - this tag is used for super contentEx: - (a+b) <sup> 2</sup><sub>: - this tag is used for subscript contentEntities :Entities are used to describe the symbols (or) special characters on tothe web page. We have certain symbols are not available on thekeyboard. So such symbols can be inserting through entities. We havemainly two types of entities they are1. Named Entity2. Number Entity1. Named Entity :Syntax: - Ampersand + entity name + semicolonEx: -&dollar;2. Number Entity :Syntax: Ampersand + hash + ascci value+ semicolonEx : &#65; =>A&#153; =>Trademark: tm
4List Tags :List tags are two types1. Order list : Grouping of elements in the form of order wisethrough number, upper alpha (A),lower alpha (a), upper roman, lowerroman is known as order listEx: - Order list.html<ol type='a' start='25'><li>Nokia</li><li>Mototola</li><li>Sony</li></html>2. Unorder list : Grouping of elements in the form of disk, squarecircle are known as unorder listEx: -<ul type='square'><li>PHP</li><li>HTML</li></ul>Definition list : This is used to maintain the heading the descriptionon to the <dl> tag.Definition term : Definition term creates the headingDefinition description : Which holds the description of the content.Dt and dd tags are both child tags of DL.Ex :<dl><dt>Terms & Conditions</dt>
5<dd><small><small>some large text matter write here</small></small></dd></dl>Meta tag :Meta tag is used to generate the traffic on to your web page. Meta tagscan be embed into the head tag using Meta tag. Meta tag helps in search engine ranking on Google page andPTC(pay to click)Ex : Meta.html<html><head><title>Meta Tags</title><meta name='keyword'content='PHP,HTML,JQUERY,CSS,HYDERABAD,Institute,Ameerpet'/><meta name='description' content='We been in lamp for more than8years and trained many student ... many have got jobs in PHP ...'/><meta http-equiv='refresh' content='5;url=http://www.axis-bank.com'/></head><body><h2>We have changed our Website Name from UTI Bank to AXISBank ... Sorry for incontinent Please wait for 5 sec it would beAutomatically be Redirected</h2></body></html>
6Link tags :Links are used to navigate from one page to another page using inter(or) external links.The attributes we can pass areTarget = “-blank” // new web pageTarget = “-new” // new web pageTarget = “-self” // open on same pageLinks can target to mails and also search the link on same page.Ex : linktag.html<html><head><title>Link Tags</title></head><body><h3>Links Navigation</h3><a href='http://www.google.com' target="_blank">Google page</a> ||<a href='http://www.facebook.com' target='_self'>Facebook Page</a>||<a href='Tags.html' target="_new"> Tags Content</a></body></html>Image tags:Images can be embed into the body tag using image tag. Images haveextension of jpg, png, gif etc.,
7Placing one image on to the web page can be done by two types theyare1.Absolute Path2.Relative Path1. Absolute path : Working from the working directory you can callthe image from anywhere with respect to its parent directory (or) outof the parent directory (or) external files.Ex :<h2>absolute path</h2><img src = ‘http://www.google.com/images/mountain.jpg’ alt =‘beautiful’ border = ‘10’ width = ‘200px’ height = ‘180px;/>2. Relative path : Using relative path you can work with images onto the same current working directory (or) sub folders did not out ofyour parent directory.Ex :<h2>relation tags</h2><img src="suresh.jpg" width='140px' height='150px' border='0'title='suresh'/><br><img src="../water lilies.jpg" width='200px' height='180px' border='3'title='suresh'/><br><img src="../../sunset.jpg" width='200px' height='180px' border='3'title='suresh'/><br><img src="new folder/dsc_0083.jpg" width='200px' height='180px'border='3' title='suresh'/><hr>Tables create :Tables are used to put down content in tabular structure. Table tag canbe embed into your body tag using<table>
8<tr> table row</tr><td> table data (or) content</td></table> The general attributes that we can pass in table tag areBorder = “<num>”Width = “<num>”Height = “<num>”Cellpadding = “<num>”Cellspacing = “<num>”Align= left/center/rightBackground = “image path”Fames = “box/group/lhs/rhs/above/below/vsides/hsidesRules = all/middle/bottomColspan =“<num>”Rowspan = “<num>”Bgcolor = “color name”Ex :<body><table border = “1” align = “center” width = “70%”><tr><td>employee detailsl</td></tr><table><tr><td>s.no</td><td>Name</td><td>designation</td></tr><tr><td>1</td><td>suresh</td><td>php programmer</td></tr></body>Cell padding : Cell padding is used to maintain the distance betweenits content and from its wall (or) borderCell spacing : Cell spacing is used to increase the wall (or) theborder
9Frame set :We can divide the body into number of divisions that are passed as anargument based on rows (or) columns working with frame set youshould ensure that body tag is not givenNote : Frame set is a depreciated tag and would be working withfuture versionsEx :<frameset cols='30%,25%,*'><frame src = 'links.html' scrolling='no' ><frame src = 'entities.html' ><frame src = 'list.html' ></frameset>Iframes :Ex :<body><p align='center'><a href='list.html' target='x'>List Page</a> | <ahref='links.html' target='x'>Links Page</a><br><br><iframe src='list.html' name='x' width='600px' height='200px'></iframe></p></body>
10
11Cascading Style Sheets(CSS)Css stands for cascading style sheet. Css is used to put some styles(or) colors on to the web page. Css can be embed into the html headtag using style tag. There are mainly 3 different flavors to attach thisstyle on to the web page. Which are mainly1. Internal style sheet2. External style sheet3. In-line style sheet1. Internal style sheet :An internal style sheet should be used when a single document has aunique style. You define internal styles in the head section of anHTML 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>2. External style sheet :An external style sheet is ideal when the style is applied to manypages. With an external style sheet, you can change the look of anentire Web site by changing one file. Each page must link to the stylesheet using the <link> tag. The <link> tag goes inside the headsection:<head><link rel="stylesheet" type="text/css" href="mystyle.css" /></head>
12An external style sheet can be written in any text editor. The fileshould not contain any html tags. Your style sheet should be savedwith .css extension. An example of a style sheet file is shown below:hr {color:sienna;}p {margin-left:20px;}body {background-image:url("images/back40.gif");}3. In-line style sheet :An inline style loses many of the advantages of style sheets by mixingcontent with presentation. Use this method sparingly!To use inline styles you use the style attribute in the relevant tag. Thestyle attribute can contain any CSS property. The example shows howto change the color and the left margin of a paragraph:<p style="color:sienna;margin-left:20px">This is a paragraph.</p>We have one more style which is given by default by browsers whichis not editableExternal style sheet can be saved with .css as its extensionSyntax :(Attributes) element (or) class (or) id {property: value ;}CSS Syntax :A CSS rule has two main parts: a selector, and one or moredeclarations:The selector is normally the HTML element you want to style.Each declaration consists of a property and a value.
13The property is the style attribute you want to change. Each propertyhas a value.Selector :Selectors are identifiers which give styles based on elements, class(denoted by period ‘.’), id (denoted by ‘#’).We have 7 kinds ofselectors.They are : Element selector Class selector Class with element selector Id selector Id with element selector Attribute selector Pseudo selector1.Element selector :Ex : element.html<html><head><title>Element Selector</title><style>h1{color:green;}</style></head><body><h1>Welcome to my Website</h1></body></html>
142.Class selector :The class selector is used to specify a style for a group of elements.Unlike the id selector, the class selector is most often used on severalelements.This allows you to set a particular style for many HTML elementswith the same class.The class selector uses the HTML class attribute, and is defined with" . (dot)"In the example below, all HTML elements with class="center" will becenter-aligned:3.Class with Element Selector :Example for Class Selector and Class with Element SelectorEx : class-selector.html<html><head><title>Class with Element Selector</title><style>h1{color:green;} //element selector.x{color:red;} // class selector//.x{font-family:impact;}p.x{font-size:20pt;color:black;} // Class with element selector</style></head><body><h1>Welcome to my Website</h1>
15<h1 class='x'>This is new Website </h1><h1>hello This is my next line</h1><p class='x'>Hello my next page</p><p>Rajesh</p></body></html>4.Id selector :The id selector is used to specify a style for a single, unique element.The id selector uses the id attribute of the HTML element, and isdefined with a "#".The style rule below will be applied to the element with id="para1":5.Id with Element Selector :Example for Id Selector & Id with Element SelectorEx : Id-selector.html<html><head><title>Id with Element Selector</title><style>h1{color:green;} //element selector.x{color:red;} // class selector//.x{font-family:impact;}p.x{font-size:20pt;color:black;} // Class with element selector#g{background:green;} //id selectorp#g{text-transform:uppercase;} //id with element selector
16</style></head><body><h1>Welcome to my Website</h1><h1 class='x'>This is new Website </h1><h1>hello This is my next line</h1><p class='x'>Hello my next page</p><p class='x' id='g'>Rajesh</p><h2 class='x' id='g'>Amith</h2><h2 class='x' id='g'>David</h3><p class='x' id='g'>Praveen</p><p class='x' id='g'>Karthik</p></body></html>6.Attribute selector :Ex : attribute.html<html><head><title>Attribute Selector</title><style>.x{color:deeppink;font-family:impact;}
17input[type='text']{color:deeppink;}</style></head><body>Name : <input type='text’ name='name' class='x'><br>username : <input type='text' name='uname'><br></body></html>7.Pseudo selector :Ex : pseudo.html<html><head><title>Pseudo Selector</title><style>p:first-letter{font-size:30pt;color:deeppink;font-family:arial black;}p:first-line{color:orange;}
18</style></head><body><p>This is my first email to all you guys his is my first email to allyou guys his is my first email to all you guys his is my first email toall you guys his is my first email to all you guys</p></body></html>Css cheat sheet :Font-styles :font-style : italic,normalfont-variant : small-caps,narmal,small,caps(capital letters)font-weight : normal,lighter,bold, bolder, number(100->light,900->bolder)font-size : <num> px;font-family : family of fontText properties :1. letter-spacing : <num>px2. word-spacing : <num>px3. line-height : <num>px4. text-align : left/center/right/justify ->order from left (or) right5. text- decoration : name, blink,underline,overline,line-through6. text-transform : capitalize(upper case/lower case(everythingconvert))7.text-indent : <num>px (distance from line to first letter)
19 The text-align property is used to set the horizontal alignment ofa text. Text can be centered, or aligned to the left or right, orjustified. When text-align is set to "justify", each line isstretched so that every line has equal width, and the left andright margins are straight (like in magazines and newspapers). The text-decoration property is used to set or removedecorations from text. The text-decoration property is mostlyused to remove underlines from links for design purposes: The text-transform property is used to specify uppercase andlowercase letters in a text.It can be used to turn everything intouppercase or lowercase letters, or capitalize the first letter ofeach word. The text-indent property is used to specify the indentation of thefirst line of a text.Background property :CSS background properties are used to define the background effectsof an element.background-color : ‘color name’;background-image : url(image path name);The background-image property specifies an image to use as thebackground of an element.By default, the image is repeated so it covers the entire element.The background image for a page can be set like this:background-repeat : no-repeat,reapt-x,reapt-y,repeat(*);By default, the background-image property repeats an image bothhorizontally and vertically.Some images should be repeated only horizontally or vertically, orthey will look strange, like this:background-attachment : fixed,scroll;
20background-position :{x,y}left,center,right,bottom,topWhen using a background image, use an image that does not disturbthe text.Showing the image only once is specified by the background-repeatproperty://background : order wiseList properties :list-style-type : none,disk,circle,square,decimal,upper-alpha,lower-alpha,upper-roman,lower-roman;list-style-position : outside (*) / inside;list-style-image:url(image path name);Box properties :Padding : inside elementMargin auto = centerOverflow = visible (*), hidden, auto, scrollEx :<html><head><title>BOX properties</title><style>//body{margin:0px;}p{text-align:center;}.z{background:#ccc;padding:15px;
21width:50%;height:80px;margin:auto;overflow:auto;text-align:justify;}</style></head><body><p><input type='checkbox' name='t&c' />Terms & Conditions<p class='z'>Some large text matter</p></p></body></html>Border Properties :border-width : <num>px;border-style : solid,groove,inset,outset,double,dotted,dashed;border-color : <color name>//border: order wiseDiv tag :Div tag stands for division tag.Div tag is the block level element. Ablock level element creates a block with coming left and right breaksin it.
22Ex : div tag, p tag, h1 to h6, table tag, ul and li tagsIn-line element : These particular elements will take the contentspan only and does not have breaks initSpan tag is the natural tag.Ex :<html><head><title>in-line element</title><style>h1 {background : green; display : inline;}b{Background: gold;}a.{text-align : center; background : yellow; display : block;}</style></head><body><h1>hello</h1><b>hello</b><i>hello</i><p>hello</p> <hr><span class = ‘a’>hello</span><div class = ‘a’>hello</div> <hr><h3> converting block & inline & respectively<h3><h1> hello</h1>
23</bold></html>Display properties :Visibility : we have visible (or) hiddenDisplay : none, in-line, block;Padding : <num>px all sidesPadding : top left0px 0pxBottom rightMargin : <num> all sidesMargin : top right bottom left0px 0px 0px 0pxTemplates :Position properties : Position in css we have absolute, relative andfixed positionRelative position : Working from the current position we can movethe element anywhere on to the web page but cannot be moved on thetop of the position place.Absolute & fixed position : Placing from the current position wecan move the element to all corner of the web page and also one topof the position place .once an element declare as fixed (or) absolutethis will turn to in-line element and this will also carry ‘7’ index initEx : position.html<html><head><title>Position properties</title>
24<style>div{background:blue;color:#fff;font-size:17pt; font-weight:bold;padding:10px;margin:4px;}.r{background:gold;color:#000;position:relative;left:30px;top:120px;}.a{background:blue;position:absolute;top:50px;left:6px;}.f{background:deeppink;color:#000;position:fixed;bottom:0px;right:0px;}</style></head><body><div>Normal Position</div><div class='a'>Absolute Position</div><div class='r'>Relative Position</div><div class='f'>Fixed Position</div><h1>some large text matter </h1><h1> some large text matter </h1><h1> some large text matter </h1><h1> some large text matter </h1></body></html>
25
26JavaScript JavaScript is client side scripting language. JavaScript is the case sensitive. JavaScript can be used for AJAX integration and validation. JavaScript can be embed into the head tag and body tag usingscript tag. JavaScript can be saved with .js as its extension.Content: Variables Datatypes Operators (Assignment, Arthamatic, Post/Pre [Inc/Dec],Comparission, Relational, Conditional, Logical,Ternary) Alert,prompt,confirm Built in Functions (Arrays,Date,Math,String) DOM (Document Object Module) Navigator,images,screen,location,history Document – (getElementById, getElementsByTagName,getElementsByName) Events : General Events (onclick(), ondblclick(), onload(),onunload(), onreset(), onsubmit(), onfocus(), onblur(),onchange()) Mouse Events (onmouseover(), onmousemove(),onmousedown(), onmouseout() ) Key Board Events – (onkeyup() , onkeydown() )Document.write () :document.write is the printing method in javascript.Which is outputstatement to the browser.Ex: first.html<html><head>
27<script src='ext.js' type='text/javascript'language='javascript'></script><script>document.write('This is Called from Head Tag<br>');</script></head><body><h1>Welcome</h1><script>document.write('This is Called from Body Tag<br>');</script></body></html>ext.js:-document.write('<h1>This is called from External Page</h1>');Variables :Variables are case sensitive. Declaring a variable in JavaScript asvariable name = value;Variables are "containers" for storing information.Ex : var a = 10; var = defaultThe correct method to declare are :Var a = 10;Var_a = 10;Var first-name = ‘suresh’;
28Var firstName = ‘suresh’;Var $name = ‘suresh’;Wrong method :Var #name = ‘suresh’;Var 1a = 10;Var first name = ‘suresh’;Data Types :String :Collection of characters inside a single (or) double quotations areknown as string ,working with single quotation and adding doublequotation in it is valid.But adding single quotation inside a singlequotation is not valid.Ex : datatypes.html<html><head><script>var a = 10;document.write('<h1>'+a);document.write(' - ');document.write(typeof(a));document.write('<br>');var f = 10.25;document.write(f);document.write(' - ');document.write(typeof(f));
29document.write('<br>');firstname = 'Rajesh';document.write(firstname+' - '+typeof(firstname)+'<br>');firstname = firstname+' Kumar';document.write(firstname+' - '+typeof(firstname)+'<br>');firstname += 'B';document.write(firstname+' - '+typeof(firstname)+'<br>');document.write('<hr>String Methods<hr>');document.write('i'll Pay the Bill Tomorrow');</script></head><body><h1>Welcome</h1></body></html>Operators :1.Assignment operator: ‘ = ‘ is used to assign values.The assignment operator ‘=’ is used to assign values to JavaScriptvariables.Ex :<script>document.write('<h1 align="center">Assignment Operator</h1>');var x = 10;
30document.write("The Value is : "+x);</script>2.Arithmetic operator: -The arithmetic operator ‘ +’ is used to add values together.Arithmetic operators are used to perform arithmetic between variablesand/or values.Ex :<script>document.write('<h1 align="center">Arthamatic Operator</h1>');a = 5; b = 3;document.write("Addition : "+(a+b)+'<br>');document.write("Multiplication : "+(a*b)+'<br>');document.write("Division : "+(a/b)+'<br>');document.write("Minus : "+(a-b)+'<br>');document.write("Modulus : "+(a%b)+'<br>');</script>3.Comparision operator :Comparision operators are used in logical statements to determineequality or difference between variables or values.Ex :<script>Document.write('<h1 align="center">comparision Operator</h1>');if(10 != '10'){
31document.write('<h2>Correct</h2>');} else {document.write('<h2>Not Correct</h2>');}document.write('<h1 align="center">Post & Pre Increment</h1>');m = 10;n = (m++)+(++m)+(m++)+(++m);document.write('The Value of m is : '+m+'<br>The Value of n is :'+n+'<br>');</script>4.Relational operator : < , > , <= , >=5.Logical operator : &&(and) -- ||(or)6.Ternary operator :Syntax for Ternary Operator :Var a= 10;Type = (a%2 == 0)? ‘even number’: ‘odd number’;//document.write(“the value you entered is : ”+type);document.write(type);Conditions :1.If else :Whenever a condition is ‘if’ it is true that part of the constructor willbe excuted.if condition is fail ‘else’ part would get executed.
32 Conditional statements are used to perform different actionsbased on different conditions use this statement to execute some code if the condition is trueand another code if the condition is falseSyntax :If (cond){//code}else{// code};2.If else if :if else if (or) ladder condition will take more than one condition (or)multiple conditions. If all the conditions fail in if else if constructorthen only else part get executed Use this statement to select one of many blocks of code to beexecutedSyntax :If(cond){//code}
33else if (cond){//code}else if (cond){//code}..else{//default value;}3.Switch :Use the case in-order wise. This is main concept in switch case Use this statement to select one of many blocks of code to beexecuted Conditional statements are used to perform different actionsbased on different conditions.Syntax :switch(n){case 1: execute code block 1
34break;case 2: execute code block 2break;default:code to be executed if n is different from case 1 and 2}Looping methods :While:do-while:Syntax:Syntax:Initialize methodInitializeWhile (cond)do{{//code//code}}1.While :Working with while loops it will first check the initialize part andchecks the condition. If condition is true it will get into theconstructor and takes place until condition fail and comes out of theconstructor. loops through a block of code while a specified condition is true
352.Do-while :This will also checks the initialized part .but for only first time it willget into the constructor and execute the code and checks theconditions later and if condition is true looping takes place (or) else itcome out of the constructor with at least single time execution code3.For-loop :For loop first initialize condition an inc/dec will be done on same(single) line for the every first time it will initialize with part themcheck within condition if condition is true the constructor will getexcuted.condition fail will come out of the for loop (constructor) Loops execute a block of code a specified number of times, orwhile a specified condition is true.Syntax :For (initialize; condition; inc/dec ){//code}Arrays :A variable which can hold more than one value is none as array (or)super variable as array can be defined is JavaScript asVar a = new Array (values); // a->super variable To find the length of the array we can go with length = arrayname.length; If the array index is been initialize more than the currentindex++ then memory is wasted in JavaScript In arrays initializing string index the printing method will notwork in JavaScriptNote : - document.write() (or) looping method will not able to printstring indexes
36 While, do-while , for-loop will not print string indexes inJavaScript so to print string indexes we can go withSyntax: - for (var name in Array name) For is key word in JavaScript which will print the string index The Array object is used to store multiple values in a singlevariable. An array is a special variable, which can hold more than onevalue, at a time.Create an Array :An array can be defined in three ways.The following code creates an Array object called myCars:1: var myCars=new Array(); // regular array (add an optional integermyCars[0]="Saab"; // argument to control array's size)myCars[1]="Volvo";myCars[2]="BMW";2: var myCars=new Array("Saab","Volvo","BMW"); // condensedarray3: var myCars=["Saab","Volvo","BMW"]; // literal arrayEx : Array.html<script>var a = new Array(10,20,30,40);document.write('The Array is : '+a+'<br>');document.write('Length of Array : '+a.length+'<br>');document.write('Index at 2 : '+a[2]+'<br>');a[2] = a[2]*2;document.write('The Array is : '+a+'<br>');a[4] = 'New Value';
37document.write('The Array is : '+a+'<br>');var b = new Array();b[0] = 100;b[1] = 200;b[2] = 300;b[3] = 400;b['Name'] = 'Rajesh';b['Age'] = 30;b[7] = 700;b[10] = 1000;document.write('<hr>Single string Index : '+b['Name']+'<hr>');document.write('The Array is : '+b+'<br>');for(i=0;i<b.length;i++){document.write('Index at : '+i+' = '+b[i]+'<br>');}document.write('<hr>');for(c in b){document.write(c+' = '+b[c]+'<br>');}document.write('<hr>');var d = [10,20,30];document.write('The Array in d is : '+d+'<br>');document.write('The Array in d is : '+d.length+'<br>');document.write('<hr>');
38var e = {'Name':'Rajesh','Age':30,10:20,'Status':'Active'};document.write('The Array in d is : '+e+'<br>');for(i=0;i<e.length;i++){document.write('Index at : '+i+' = '+e[i]+'<br>');}for(c in e){document.write(c+' = '+e[c]+'<br>');}</script>Double dimensional array:An array can have more than one array is called double dimensionalarray.Ex : douledimensionarray.html<html><head><script>var a =[[1,'Ajay',[45,62,49,72,55,84]],[2,'Rajesh',[48,62,94,72,38,62]],[3,'Suresh',[48,63,82,97,45,28]]];//document.write(a[1][1]);document.write('Name is : '+a[2][1]);document.write("<table border='1' align='center' width='60%' >");document.write("<tr><th colspan='9'>Student Marks Memo Report</th> ");
39document.write("<tr><td rowspan='2'>Roll No</td> <tdrowspan='2'>Name</td><td colspan='6'align='center'>Subjects</td><td rowspan='2'>Pass/Fail</td></tr>");document.write("<tr><td>English</td><td>Hindi</td><td>Telugu</td> <td>Maths</td><td>Science</td><td>Social</td></tr>");document.write("<tr><td>"+a[0][0]+"</td></tr>");</script></head><body><tr><td><script>document.write(a[1][0]);</script></td><td><script>document.write(a[1][1]);</script></td></tr></table></body></html>Array built-in Functions :Join : Join is the pre-defined key-word in the JavaScript .which willconvert the given array into the separator passed default separator iscoma (,).Concat : concat is joining more than array in single array is calledconcat.Reverse : reverse in JavaScript the array last being is first. First islast without (descending order) the original array will also getaffected. If we use reverse function.Sort : sort is nothing but given the order is ascending order .Unshift : unshift will add the value at the starting of the array. Thevariable use for unshift will holds the length of the array and theoriginal array would get affected.
40Shift : shift function will not hold any arguments should will removethe starting value of the array.The variable unshift will hold theremoved value.Push : push is nothing but insert the value into the array at the end ofarray is called push.Pop : pop is nothing but remove the last value in the array is calledthe pop.Ex : arraybuiltin.html<script>var a = new Array('This','is','my','new','car');document.write('The Original Array is : '+a+'<br>');b = a.join(' ');document.write('Join Method : '+b+'<br>');var a = new Array(10,20,30);var b = new Array(40,50);var c = new Array(60,70,80);document.write("Concat Two Arrays : "+a.concat(b)+"<br>");document.write("Concat All Given Array : "+a.concat(b.concat(c))+"<br>");var a = new Array('Ajay','Raju','Amith','Zebra','Arjun');b = a.reverse();document.write("Reverse of an Array : "+b+'<br>');document.write("Original Array : "+a+'<br>');var a = new Array('Ajay','Raju','Amith','Zebra','Arjun');b = a.sort();document.write("Assending Order : "+b+'<br>');
41document.write("Original Array : "+a+'<br>');b = a.reverse();document.write("Reverse With Desending Order : "+b+'<br>');document.write("Original Array : "+a+'<br>');var x = new Array(10,20,30);b = x.unshift(5);document.write("Unshift Method : "+x+'<br>');document.write("The Value Stored in B : "+b+'<br>');var x = new Array(5,10,20,30);b = x.shift();document.write("shift Method : "+x+'<br>');document.write("Removed Value is stored B : "+b+'<br>');var x = new Array(5,10,20,30);b = x.push(40);document.write("Push last Value to Array Method : "+x+'<br>');document.write("B holds the length of the Array: "+b+'<br>');var x = new Array(5,10,20,30);b = x.pop();document.write("Pop Removes last Value in Array : "+x+'<br>');document.write("B holds the Removed Value: "+b+'<br>');</script>Functions:-Functions in javascript are case sensitive once declare a functionname and try to re-declare. The same function name will overwriteprevious function name. Functions are used to debug the code and
42analize the errors easily. Working with length of the code will bereduced.We have mainly 4 types of the functions in JavaScript that is1. Function without arguments and return value2. Function with arguments and no return value3. Function with return value and no arguments4. Function with arguments and return valueSyntax :Function function name (arguments, arg){//code}1. Function without arguments and return valueEx :<script>test();function test(){document.write('This is Function without Aurgument<br>');document.write('This is my function Content<br>');}function test1(){document.write('Overwritten is done on the previous printingmethods<br>');}test();
43test();</script><body><script>test();</script></body>2. Function with arguments and no return valueEx :<style>.error{background:gold;color:green;padding:10px;margin:auto;width:60%;font-size:18pt;}.success{background:black;color:#fff;padding:10px;margin:auto;width:60%;font-size:18pt;}</style><script>function welcome(name){document.write("Welcome ! "+name+'<br>');}welcome('Rajesh');welcome('Amith');function statement(type,message){document.write("<div class='"+type+"'>"+message+"</div>");}//statement("error","Welcome Guest ! ");
44statement("success","Welcome Rajesh");</script>3. Function with return value and no argumentsEx :<script>function test(){document.write('This is line 01<br>');document.write('This is line 01<br>');return 10 2;document.write('This is line 01<br>');document.write('This is line 01<br>');}test();var x = test();document.write('The Value in x is : '+x+'<br>');</script>4. Function with arguments and return valueEx :<script>function square(num){return num*num;}document.write('The Square root of 5 is : '+square(5)+'<br>');document.write('The Square root of 5 is : '+square(square(5))+'<br>');
45</script>Math built-in function :In JavaScript we have mainly seven kinds of math objects which arepre-defined and can be called respective key-words. Which areincluded in JavaScript library.Ex : math.html<script>function r(txt){document.write('<h2>'+txt+'</h2>')}r("<u>Javascript Predefined Math Constant Object </u>");r('Eulers Constant : '+Math.E);r('Pi Value : '+Math.PI);r('SQRT OF 2 : '+Math.SQRT2);r('Natural Log 2: '+Math.LN2);r('Natural Log 10 : '+Math.LN10);r('Log base 2 of Eulers : '+Math.LOG2E);r('Log base 10 of Eulers : '+Math.LOG10E);r("<u>Javascript User - defined Math Object </u>");r('Max Value : '+Math.max(10,20,30));r('Min Value : '+Math.min(10,20,30));r('Sqrt Value : '+Math.sqrt(25));r('2 pow 4 : '+Math.pow(2,4));r('Absolute Value : '+Math.abs(-9));
46r('Ceil Value : '+Math.ceil(2.11111));r('floor Value : '+Math.floor(2.9999));r('round Value : '+Math.round(2.5111111));r('Random Number : '+Math.random());r('Number Between 1 to 1000 : '+Math.round(Math.random()*1000));</script>String built-in functions :Ex : stringbuilt.html<script>function r(txt){document.write(txt+'<br>');}var str = "lamp Institute";r('String Value = '+str);r("Length of the String = "+str.length);r("Color of String = "+str.fontcolor('green'));r('Upper Case = '+str.toUpperCase());r('Lower Case = '+str.toLowerCase());r('Big Font = '+str.big());r('Bold Font = '+str.bold());r('Small Font = '+str.small());r('Italic Font = '+str.italics());r('Superscript = '+str.sup());r('sub script = '+str.sub());
47r('<hr><h2><u>Slice Function([begin, stop]) </u></h2>');r('Slice(4) = '+str.slice(4));r('Slice(4,8) = '+str.slice(4,8));r('Slice(-9) = '+str.slice(-9));r('Slice(-9,8) = '+str.slice(-9,8));r('Slice(-9,-3) = '+str.slice(-9,-3));r('<hr><h2><u>Substring Function([From, to]) </u></h2>');r('substring(4) = '+str.substring(4));r('substring(4,8) = '+str.substring(4,8));r('substring(4,2) = '+str.substring(4,2));//r('substring(-9) = '+str.substring(-9));r('<hr><h2><u>substr([start, length]) </u></h2>');r('substr(4) = '+str.substr(4));r('substr(5,8) = '+str.substr(5,8));r('substr(-9) = '+str.substr(-9));r('substr(-9,2) = '+str.substr(-9,1));r('CharAt(0) = '+str.charAt(1));r('charCodeAt(1) = '+str.charCodeAt(1)); //ascill Value of Indexmob = 'Z123456789';r('charCodeAt = '+mob.charCodeAt(0));r('Indexof = '+str.indexOf('T'));//-1r('lastIndexof = '+str.lastIndexOf('t'));r('indexOf = '+str.indexOf('t',9));r('Search = '+str.search('z'));//-1
48r('Match = '+str.match('z'));//null</script>Mobile function :Ex : mob.html<script>function r(txt){document.write(txt+'<br>');}mob = "8855644045";r(isValidMobile(mob));function isValidMobile(val){if(val.length != 10){return "Please Enter 10-Digit Mobile Number";}f = val.charAt(0);if(f == '7' || f == '8' || f == '9'){} else {return 'Please Check the First Digit of Number & tryAgain';}return isNumeric(val);}function isNumeric(val){for(i=0;i<val.length;i++){
49ascii = val.charCodeAt(i);if(ascii < 48 || ascii >57){return 'Only Numbers Allowed Please Check again';}}return 'Valid Mobile Number';}</script>Date functions: -Date function can be defined with variable is equal to new date. Thisfunction is pre-defined in JavaScript which will explain the systemtiming (or) running the domain it will capture the running domain.Get time () : This is unique time constant which is created findgenerate number of milliseconds right from night jan 1st 1970.Ex : date.html<script>function r(txt){document.write(txt+'<br>');}var d = new Date();r('The value in d is : '+d);r('Unix Time Constant that is Midnight Jan 01,1970 (no ofmillseconds : ) '+d.getTime());r('Date : '+d.getDate());r('Day : '+d.getDay());
50r('Month : '+(d.getMonth()+1));// 0 -11r('Year : '+d.getYear());//works only in ie...r('FullYear : '+d.getFullYear());r('Hours : '+d.getHours());r('Minutes : '+d.getMinutes());r('Seconds : '+d.getSeconds());r('Time is : '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());</script>DOM :DOM contains these layers1.IMAGES2.LOCATIONS3.SCREEN------------------> Get Element ById4.DOCUMENTS-----------> GetElementByTagName5.NAVIGATOR------------ > GetElementByName6.EMBEDEx : dom.html<script>function dochange(){document.testForm.fname.value = alert("Please Enter");document.testForm.fname.value = 'Enter Name';document.testForm.lname.style.border="2px solid red";document.testForm.lname.style.width="200px";}
51</script><body><form name='testForm'>First Name : <input type='text' name='fname' /><br>Last Name : <input type='text' name='lname'/><br><input type='button' name='change' value='DoChange'onclick="#
52</form></body>GetElementByTagName :This particular function will match tag name and excute the functionwhich we are passing as a tag nameEx : getElementsByTagName.html<script>function dochange(){var a = document.getElementsByTagName('div');for(i=0;i<a.length;i++){a[i].style.width = '400px';a[i].style.background = '#ddd';a[i].style.border = '4px dotted green';}}</script><body onmouseover='dochange();'><h1>Welcome to My Web Page</h1><p>This is my First Page</p><p>This is my First Page</p><p>This is my First Page</p><p>This is my First Page</p><div>What is Social Hub</div></body>
53GetElementByName :This particular function will match element name and that part of thefunction will get excutes.Ex : getElementsByName.html<script>function dochange(){var a = document.getElementsByName('x');for(i=0;i<a.length;i++){a[i].style.width = '400px';a[i].style.background = '#ddd';a[i].style.border = '4px dotted green';}}</script><body onmouseover='dochange();'><h1>Welcome to My Web Page</h1><p>This is my First Page</p><p>This is my First Page</p><p>This is my First Page</p><p>This is my First Page</p><div>What is Social Hub</div></body>Note 1 : As ids are unique we have singular matching so we cangetElementById as singular.
54Note 2 : GetElementByTagName & ByName works the array formatand these are plural.Events :Whenever an event is trigger and then that particular matchingfunction will excuted.a)innerHTML : innerHTML is used to push the dynamic values onto the HTML page.b)set Interval : setInterval is pre-defined key-word in JavaScriptwhich takes 2 arguments the first argument can be expression (or)function the second argument can be number of milliseconds.c)Alert : Alert gives you a single button option until it is click It willallowed you to navigate on the server.Ex : alert.html<script>alert("Please Agree with Our Terms & condition");</script><body>Welcome</body>d)Confirm : Confirm is used two options until something is beingclick. It won’t allowed to navigate the server and if it is click based onthe values it will moved to the respect pages.Ex : confirm.html<script>var x = confirm("Are You legally 18+ then enter to site");if(x == true){document.write("Welcome to my Terrorist Site");
55} else {document.write("Thank You for leaving Please <ahref='http://www.google.com'>Click Here</a>");}</script><body></body>e)Eval : Eval is pre-defined function in JavaScript which willevaluate the given function in between the JavaScript (function)f)parseINT : This is pre-defined function in JavaScript which willconvert the floating value into integer value.g)parseFLOOT : This is pre-defined function in JavaScript whichwill convert the integer value into floating value.Ex : innerHTML & set Interval time.html<script>function r(txt){document.write(txt+'<br>');}function currTime(){var d = new Date();var time =timeFormat(d.getHours())+':'+timeFormat(d.getMinutes())+':'+timeFormat(d.getSeconds());return 'Present Time : '+time;}function timeFormat(val){return ((val<10)?'0':'')+val;
56}function writeTime(id){return document.getElementById(id).innerHTML = currTime();}</script><body><div id='currentTime' align='right'><script>r(currTime());setInterval("writeTime('currentTime')",1000);</script></div></body>
57
58PHP Rasmus Lerdorf is the founder of the PHP in 1995. PHP is the server side scripting language. Php needs a server to excute the file. Php files should be saved with .php as its extension ".php3", or".phtml" Or else our server will not excute unknown extension apart from.html, .cpi, .cgs, Php supports all the data bases that are present in the marketEx:-mySql,mssql,infonix,Sybase,ibmdb2,postgresql………etc Php can be worked on all the operating systems that iswindows,linux,max,solaries…etc Php can communicate with different serversEx:-SMTP(Simple mail transfer protocal), imap (internet maxaccess protocal), LDAP, Informix, Oracle, Sybase, Solid,PostgreSQL PHP can be install as a software tags we get many of the serverfilesEx : Xampp, Wamp, easy php, mamp PHP stands for PHP: Hypertext Preprocessor PHP is an open source software PHP is free to download and use PHP is easy to learn and runs efficiently on the server sideXampp : Xampp stands forx------------------------>platform(windows,linux,mac,solaries)a------------------------->apache(web server)m------------------------>mysql(database file)p------------------------->perl(perl scripting in php)p------------------------->php/my admin (web database tool)php current version is 5.3.8
59Wamp : Wamp stands forw------------------------>window exva------------------------>apache(web server)m------------------------>mysql(database file)p------------------------>php/my admin (web database tool)Mamp : Mamp stands form------------------------>mac ‘os’a------------------------->apache(web server)m------------------------>mysql(database file)p------------------------->php/my admin (web database tool)Apache contain the 1-65535 ports.In that 1-1024 are pre-reservedports.Tmp : Tmp holds session details & temp upload files.Htdocs : After installing xampp we have to store our files into thefolder called htdocs. Once files are saved in htdocs we can open withthe location path ashttp://localhost/abc(foldername)/first.phpEcho : echo is the output method in php.Basic PHP Syntax :<?phpecho “universal way of writing php<br>”;?><script language = ‘php’>
60echo “javascript way of writtting php<br>”;</script><?echo”short tag way of writing php<br>”;?><%1echo “asp way of writing php<br>”;%>Comments in PHP :In PHP, we use // to make a one-line comment or/* and */ to make a comment block<html><body><?php//This is a comment/*This isa commentblock*/?></body></html>
61Printing methods in php :a.Echo : echo is an argument can print multiple arguments. Echo as afunction can print only one argument.b.Print : print is an argument can print only one argument.print also afunctionEx: - print”arg<br>”;c.Printf : printf will take formatting string with respected values asprintEx : printf(“(int%d) (float%f) (string %s) (asci%c)”);d.Print-r : print-r will print array of stringEx: - $g = array (10,20,30,true,’kalam’);Print-r($g);e.Var-dump : It is also printing method which is used debugging theerrors very easily. This not used in production level (liveenvironmental )Ex : var-dump($g);<h1>Printing Methods in PHP</h1><?php$a = 10; $b = 20; $c = 30;echo "Arg01","Arg02","Arg03<br>";echo $a,$b,$c,'<br>';echo ("Arg01<hr>");print "Arg01<br>";print("Arg01<hr>");
62printf("(int %d) (float%.2f) (string %s) (Ascii %c)",22.25,10.2545,'Rajesh',97);echo '<hr>';$g = array(10,20,30,true,'Rajesh');print_r($g);echo '<hr>';var_dump($g);?>Controlling :Ex : controlling.php<style>b{color:green;}</style><?phpecho "line 01<br>";echo "line 02<br>";echo "line 03<br>";?><b>This is Bold Tag</b><hr><?phpif(false){echo "<b>The 1<sup>st</sup> is Executed<br></b>";} else {echo "<b>The 2<sup>nd</sup> is Executed<br></b>";
63}?><hr><h2>Alternate Method</h2><?phpif(true){?><b>The 1<sup>st</sup> is Executed<br></b><?php}else{?><b> The 2<sup>nd</sup> is Executed<br></b><?php}?>Variables : Variables are "containers" for storing information. Variables in PHP starts with a $ sign, followed by the name ofthe variable. The variable name must begin with a letter or the underscorecharacter. A variable name can only contain alpha-numeric characters andunderscores (A-z, 0-9, and _). A variable name should not contain spaces.
64 Variable names are case sensitive (y and Y are two differentvariables).Ex : variables.php<h1>Variables in php</h1><?php$a = 10;$name = 'Rajesh';$_name$_name$n123$_1232$1_name$first_Nameecho 'The Value is : ',$a.'<br>';echo 'The Name is : ',$name,'<br>';?><script>var a = 15;document.write('The Value of a is : '+a+'<br>');</script> In PHP, a variable does not need to be declared before adding avalue to it.
65 In the example above, notice that we did not have to tell PHPwhich data type the variable is. PHP automatically converts the variable to the correct data type,depending on its value. In a strongly typed programming language, you have to declare(define) the type and name of the variable before using it.PHP has four different variable local global static Super global array variableLocal variable : A variable declared within a PHP function is localand can only be accessed within that function.Ex : localvariable.php<?phpfunction test(){$a = 10;echo 'The Value of $a inside function is : ',$a,'<br>';}test();echo 'The Value of $a Outside Function is : ',$a,'<br>';?>Static variable : When a function is completed, all of its variablesare normally deleted. However, sometimes you want a local variablenot to be deleted.To do this, use the static keyword when you first declare the variable.
66Ex : staticvariable.php<?phpfunction test(){$a = 10;static $b = 20;echo 'The Value of $a inside function is : ',$a,'<br>';echo 'The Value of $a inside function is : ',$b,'<br>';$a++;$b++;}echo 'The Value of $b outside is : ',$z,'<br>';test();test();?>Global variable : Global scope refers to any variable that is definedoutside of any function.Global variables can be accessed from any part of the script that is notinside a function.To access a global variable from within a function, use the globalkeyword:Ex : global.php<?php$x = 10;
67echo 'The Value of $x = ',$x,'<br>';function test(){//global $x;echo 'The Value of $x inside Function = ',$x,'<br>';echo '$GLOBALS["x"] = ',$GLOBALS['x'],'<br>';}test();?>Super global array variable : ‘$ global’ is the super global arrayvariable. This is the pre-defined keyword. In php we have mainlysome of the super global variables. This can be used with theirkeywords.i) $_EVN : This is used for getting the information of your operatingsystem ($_ENV (PATH))ii) $_SERVER : This will give you the information about yourserver(apache information)iii) $_GET : It is used for form processing through get method (or)query stringiv) $_POST : This is used for form processing through post methodin secure mannerv) $_REQUEST : It will send the form through both get and post andcookievi)$_COOKIE : This is used to get the information about the browserwho is using the web(computer)vii)$_SESSION : It is used to get the information of the user inbetween login and logout details are store at server machine.
68Operators :1. Assignment operator: = is used to assign values to variables inPHP2. Arithmetic operator: +,-,/,*,%3. Increment & decrement operator: i++,++I & i--, --i4. Comparison operator: ==,!= ,===5. Relational operator: <=, >=, <>6. Logical operator: &&, ||, and, or7. Error handling operator :8. Scope resolution & this operator : ::----->scope, &------->thisEx : operator.php<?phpecho '<h1 align="center">Assignment Operator</h1>';$a = 10;echo 'The Value is : '.$a.'<br>';echo 'The Value is Added by 2 : ',$a += 2,'<br>';$name = 'Rajesh';echo 'My name is : '.$name,'<br>';$name .= ' Kumar';$name = $name.' Kumar';
69echo 'My name is : ',$name,'<br>';echo '<h1 align="center">Arthamatic Operator</h1>';echo 'The value of 2+3 : ',2+3,'<br>';echo 'The Value of 2-3 : ',2-3,'<br>';echo 'The Value of 2/3 : ',2/3,'<br>';echo 'The Value of 2*3 : ',2*3,'<br>';echo 'The Value of 2%3 : ',2%3,'<br>';echo '<h1 align="center">Increment & Decrement [INC/DEC]</h1>';echo '<h2>POST & PRE increment</h2>';$x = 10;echo 'The Value of $x = ',$x,'<br>';echo 'The Value of $x++ = ',$x++,'<br>';echo 'The Value of $x = ',$x,'<br>';echo 'The Value of ++$x = ',++$x,'<br>';echo 'The Value of $x = ',$x,'<br>';echo '<h2>POST & PRE Decrement</h2>';echo 'The Value of $x-- = ',$x--,'<br>';echo 'The Value of $x = ',$x,'<br>';echo 'The Value of --$x = ',--$x,'<br>';echo 'The Value of $x = ',$x,'<br>';echo '<h1 align="center">Comparision Operator</h1>';
70var_dump(10 == 10);echo'<br>';var_dump(10 != '10');echo'<br>';echo '<h1 align="center">Relational Operator</h1>';var_dump(10<=10);echo '<br>';var_dump(10<>'10');echo '<br>';//not Equal toecho '<h1 align="center">logical Operator</h1>';var_dump(true && true);echo '<br>';var_dump(true && false);echo '<br>';var_dump(true || true);echo '<br>';var_dump(true || false);echo '<br>';var_dump(false AND FALSE);echo '<br>';var_dump(false OR FALSE);echo '<br>';echo '<h1 align="center">Error Handling Operator</h1>';echo @sqrt();//@test();echo 'Some Data';echo '<h1 align="center">Scope Resolution & this Operator {:: & ->(this)}</h1>';class A{static $z = 100;public $a = 20;public $k = 50;
71protected $b = 30;private $c = 40;function test(){echo "A Test Function called inside Class A";}}$obj = new A;echo $obj->a,'<br>';echo $obj->k,'<br>';//echo $obj->b,'<br>';//echo $obj->c,'<br>';echo ' The Static Value is : ',A::$z,'<br>';echo 'The Function inside Class is : ',$obj->test(),'<br>';?>Type Casting: -Conversion of the one data type into another data type is known astype casting. in php we have mainly two types of costing1. Temporary type casting2. Permanent type casting1. Temporary type casting : Casting which can be done for singlestep by pre-defined the data type keyword. That particular variablewill hold Temporary type casting.
72Ex : temporary.php<?php$x = "10.254Kgs";var_dump($x);echo "<br>";var_dump((int)$x); echo "<br>";var_dump($x); echo '<br>';var_dump((float)$x); echo '<br>';var_dump((boolean)$x);echo'<br>';var_dump((string)$x);echo "<br>";var_dump($x);echo "<br>";var_dump(floatval($x)); echo '<br>';var_dump(intval($x)); echo '<br>';var_dump($x);echo "<br>";?>2. Permanent type casting : This can be done by using pre-definedkey-word set type.which hold two argumentsSyntax : set type (var name,’int’);Ex : Permanent type casting.php<?phpecho '<h1>Permanent Type Casting</h1>';$x = "10.254Kgs";
73settype($x,'float');var_dump($x);echo "<br>";settype($x,'int');var_dump($x);echo "<br>";settype($x,'boolean');var_dump($x);echo "<br>";settype($x,'int');var_dump($x);echo "<br>";var_dump($x);echo "<br>";settype($x,'float');var_dump($x);echo "<br>";?>Type juggling : conversion of data types by using expression toanother data types are known as type juggling.Ex : typejuggling.php<?phpecho 'true + true : ',true+true,'<br>';if(null){echo "Printed";} else {echo "Not Printed";
74}?>Variable validation function :i) Isset : Isset of variables will check with the variable initialize ornot and return Booleanii) empty(var name) : empty function will check the variablewhether it is null or not and return Booleaniii) Unset (var name) : This function will remove the variable (or)delete the variableiv) get type(var name) : This function will let us know the argumentdata type in the form of string ,this should be used because thecoming variable would be depreciated.Ex : variable_validation.php<?php$x = 10;var_dump($x);echo '<br>';var_dump(isset($x));var_dump(isset($a));echo '<hr>';$z = '';var_dump(empty($z));var_dump(empty($y));$k = 10;echo '<br>';var_dump(gettype($k));
75unset($x);var_dump(isset($x));?>Data Types :Php supports mainly 8 kinds of data types among which four arestable data types, two are compound data types and another two arespecial data typesa)Stable data types :i) int (or) integerii) Float (or) real (or) decimaliii) Boolean data typesiv) string data typesi)int (or) integer : All non decimal values . range in between 2(32-1)to -2(32-1)Ex :<?phpecho "<h1 align='center'>Stable Data types</h1>";echo "<h2>Integer Data Type</h2>";$x = 10;var_dump($x);echo '<br>';$x = (pow(2,32-1)-1);var_dump($x); echo '<br>';
76$judge = 2147483647;var_dump($judge);?>ii) Float (or) real (or) decimal : All decimal values. Range inbetween 10(38) to 10(-38)Ex :<?phpecho "<h2>Float Data Type</h2>";$a = 10.25;var_dump($a);echo '<br>';?>iii) Boolean data types : Boolean data types return the values in theform of true (or) falseEx :<?phpecho "<h2>Boolean Data Type</h2>";$a = false;var_dump($a);?>iv) String data types : Collection of characters enclose in betweensingle (or) double cotations are known as string data types.
77Ex :<?phpecho "<h2>String Data Type</h2>";$x = 10;echo '<br>The Value of $x is ',$x,'<br>';echo "The Value of $x is :$x";$name = "Rajesh";echo '<br>my name is $name <br>';echo "my name is $name <br>";$x = 10;$y = 20;echo 'The value of $x+$y = ',$x+$y,'<br>';echo "The value of $x+$y = ",$x+$y,'<br>';?>b)Compound data types :Compound data types again two types1. Array data type2. Object data type1. Array data type : Array data type which can hold more than onevalue. In php we have mainly 3 kinds of arraysi) Numerical arrayii) Associative array
78iii) Mixed arrayDeclaring an array in php can be done by two types array as the function array as a square bracketi) Numerical array :A numeric array stores each array element with a numeric index.There are two methods to create a numeric array. In the following example the index are automatically assigned(the index starts at 0):$cars=array("Saab","Volvo","BMW","Toyota"); In the following example we assign the index manually:$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota";Ex :<?php$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota";echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";?>ii) Associative array :An associative array, each ID key is associated with a value.
79When storing data about specific named values, a numerical array isnot always the best way to do it.With associative arrays we can use the values as keys and assignvalues to them.Example 1In this example we use an array to assign ages to the differentpersons:$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);Example 2This example is the same as example 1, but shows a different way ofcreating the array:$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";The ID keys can be used in a script:<?php$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";echo "Peter is " . $ages['Peter'] . " years old.";?>The code above will output:Peter is 32 years old.iii) Mixed array :Mixed array is nothing but combination of numerical & associativearray is known as mixed array.
80Ex : mixedarrays.php<?php$a = array("Name"=>"Rajesh","Age"=>30);print_r($a);echo '<hr>';echo '<h1 align="center">Mixed Arrays</h1>';define('A','ABC');define('B','XYZ');$c = 10;$d = 20;$g =array(0=>10,1=>20,'Name'=>'Raj','Age'=>30,5=>500,5.55=>600,-9=>'Negative value',true=>200,false=>200,''=>'EmptyValue',NULL=>'Null Value',A=>B,$c=>$d);echo '<pre>';print_r($g);echo '</pre>';?>2. Object data type :Object is an instance of class.Class can be denoted with in class name.Collection of variables and functions are known as class.For Callingclass we should create an object then that particular variable isknown as object variable.
81Ex :<?phpecho "<h2>Object Data Type</h2>";class A{public $x = 10;public $a = 20;function test(){echo 'A test Function called<br>';}}$b = new A;var_dump($b);echo '<br>Public Value $x = ',$b->x,$b->test(),'<br>';?>Special data types :Special data types are again two typesi) Resource data typesii) Null data typesi) Resource data types : Resource data type is calling an externalvariable value into another variable using (&) resource variable.
82ii) Null data types : This is the pre-defined key-word. When avariable not initialize and by asking through printing method. Thiswill result in null value.Ex :<?phpecho "<h1 align='center'>Special Data types</h1>";echo "<h2>Reference Data Type</h2>";$x = 10;$y = $x;echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<br>';$x = 12;echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<br>';$y = 'Rajesh';echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<hr>';echo "<h2>Resourse Data Type</h2>";$a = 10;$b = &$a;echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';$a = 'Raj';echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';$b = 'Amith';echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';
83echo "<h2>Null Data Type</h2>";var_dump($z);?>Constant :Define : Define is the pre-defined key-word in php. This will taketwo arguments. The first argument being the constant identifier whichidentifier its second argument value. We can pass third argument asBoolean to make case in-sensitiveEx : constant.php<?phpdefine('x',10,true);echo x,'<br>';echo X;echo '<hr>';define('url','http://www.socialhub.com',true);echo uRl,'/register.php';echo '<hr>';define('SITE_NAME','http://www.socialhub.in-hyderabad','SocialHub');?><h1>About us</h1>we at <?php echo SITE_NAME;?> are in training ........<h1>Contact Us</h1>
84<?php echo SITE_NAME;?>street ......<h1>FAQ</h1>what we do at <?php echo SITE_NAME;?>Conditions :Conditional statements are used to perform different actions based ondifferent conditionsa)If condition :IN PHPIN PERLIf (cond)if (cond) :{//code//codeelse if (code) :}//codeelse if (cond)else (cond) :{//code//codeend else if ;}
85else (cond){//code}b)Switch condition :Syntax :switch (cond) :switch (cond):{|Case1 :|//code|Break;|Case2://code|Break;end switch;||Default://code}
86Ex :<html><body><?php$x=1;switch ($x){case 1:echo "Number 1";break;case 2:echo "Number 2";break;case 3:echo "Number 3";break;default:echo "No number between 1 and 3";}?></body></html>c)While condition : The while loop executes a block of code while acondition is trueSyntax:While (cond)while (cond):{//code inc/dec//const code inc/decendwhile}
87Ex:<html><body><?php$i=1;while($i<=5){echo "The number is " . $i . "<br />";$i++;}?></body></html>d)Do-while condition : The do-while statement will always executethe block of code once, it will then check the condition, and repeat theloop while the condition is true.Syntax :Do do:{ //codeInc/dec//code enddowhile(cond);}While (cond)Example :The example below defines a loop that starts with i=1. It will thenincrement i with 1, and write some output. Then the condition ischecked, and the loop will continue to run as long as i is less than, orequal to 5:<html><body>
88<?php$i=1;do{$i++;echo "The number is " . $i . "<br />";}while ($i<=5);?></body></html>e)For loop : Loops execute a block of code a specified number oftimes, or while a specified condition is true. The for loop is used whenyou know in advance how many times the script should run.Syntax :For(initialize;cond;inc/dec)//codeend forExample :The example below defines a loop that starts with i=1. The loop willcontinue to run as long as i is less than, or equal to 5. i will increaseby 1 each time the loop runs:<html><body><?phpfor ($i=1; $i<=5; $i++){echo "The number is " . $i . "<br />";}?></body></html>
89f)for each : for each is usefull for all non-sequence data of an array.Associative array ,numerical array object data of an array.The general syntax isforeach (arrayName as arr[value])){echo arr [value];}Another syntax isforeach (arrayname as key=>value){echo key’-‘value (or) echo “key-value”;}Ex : foreach.php<?php$a = array("Name"=>"Rajesh","Age"=>30);/*foreach(arrayname as value){echo arr[value];}*/foreach($a as $v){echo $v,'<br>';}echo '<hr>';/*foreach(arrayname as key=>value){echo key,' - ',value;}*/foreach($a as $k=>$v){
90echo "$k - $v<br>";//echo $k,' - ',$v,'<br>';}?>Functions :Functions are case in-sensitive.Once function can be declare con’t bere-declare in the program.The real power of PHP comes from its functions.In PHP, there are more than 700 built-in functions.To keep the script from being executed when the page loads, you canput it into a function.A function will be executed by a call to the function.You may call a function from anywhere within a page. Give the function a name that reflects what the function does The function name can start with a letter or underscore (not anumber)Syntax:function function name (arg){//codeReturn value}There are mainly 8 kinds of functions in php
911. Conditional Function : A function which is enclose insidecondition is considered as conditional functionEx : conditional.php<?phpif(false){function test(){echo "I am a Conditional Function <br>";}}@test();2. Variable Function : When a function name is told In variable.Variable can be used for excuting the function in a place of functionnameEx : variables.php?phpfunction test(){echo "I am a Variable Function <br>";}test();$a = 'test';echo $a;echo '<br>';$a();$a();3. Function Function : Function is define inside another function iscalled as function-function.
92Ex : function's function.php<?phpFunction parent f(){echo “iam write the function function<br>”;If(!function_exists(childF)){function child F(){echo “I need some one to open parent file for me to excute<br>”;}}}Parent F();Child F();Parent F()’?>4. Function with arguments : Function can be defined with one (or)more arguments. If arguments are not passed then it creates warningin the programEx :<?phpfunction test($x,$y){echo 'The Value of $x = ',$x,'<br>';echo 'The Value of $y = ',$y,'<br>';}
93test('Raj','Kiran');test(10,20);test('Amith');test();?>5. default argument : A function at the time of a declaration ifargument are assign with some values they will be treated as optional(or) default argument value and they can be passed with value (or)can left without passing the value. Works at the side default argumentmust be passing last in the program at the argument listEx :<?phpfunction test($x=10,$y=20){echo 'The Value of $x = ',$x,'<br>';echo 'The Value of $y = ',$y,'<br>';}test(100,200);test('Raj','Kiran');test();?>6. Overloaded argument : A function can be define with argument(or) that the defined arguments they are still acknowledge inside thefunction using various pre-defined functioni) func_num_args() : return the total number of arguments which arepassed in the function
94ii) func_get_args() : return the array with all the arguments with thefunctioniii) func_get_args(position) : return the argument value at thespecified positionEx :<?phpfunction test(){echo "<h1>Overloaded Concept</h1>";echo 'The Overloaded Length = ',func_num_args(),'<br>';print_r(func_get_args());echo '<hr>';for($i=0;$i<func_num_args();$i++){echo 'Index at : ',$i,' - ',func_get_arg($i),'<br>';}echo '<hr><h1>For Each Method</h1>';$y = func_get_args();foreach($y as $k=>$v){echo "$k => $v<br>";}}test(10,20,'Rajesh');7. Function with Return value : Return key-word can be stop theexecution of the function.Return key-word can optionally followedwith a value which is return variable.Whenever a function is validanother one value con’t be passed after the return statement multiplevalue con’t be club as array (or) object and con’t be return wherever afunction is called.
95Ex :<?phpfunction test(){echo "This is Return Information<br>";//return 10;echo "I am second info<br>";return = 82;echo "I am second info<br>";}test();$y = test();echo $y;//echo $y;8. i) arguments passed by value : When an argument passed byvalue any change for the value inside the function owned be reflectedin the variable outside the functionii) Arguments passed by reference : When an argument passed byresource and change for the inside with be refer to the variable outsidethe functionEx :<?phpfunction test($x,&$y){$x +=2;$y +=10; // $y = $y+10;echo 'The Value of $x = ',$x,'<br>';
96echo 'The Value of $y = ',$y,'<br>';}$a = 5;$b = 10;echo '$a = ',$a,'<br>';//5echo '$b = ',$b,'<br>';//10test($a,$b);echo '$a = ',$a,'<br>';//5echo '$b = ',$b,'<br>';//10?>Built-in Functions :a)Math Functions :Ex :<?phpecho 'Math Pi Value = ',M_PI,'<br>';echo 'Math Pi Value = ',M_PI_2,'<br>';echo 'Math Pi Value = ',M_PI_4,'<br>';echo 'Eulers Constant = ',M_E,'<br>';echo 'SQRT 2 = ',M_SQRT2,'<br>';echo 'SQRT 2 = ',M_SQRT1_2,'<br>';echo 'Log of 2 = ',log(2),'<br>';echo 'Log base 10 of 2 = ',log10(2),'<br>';echo 'Absolute Value = ',abs(-9),'<br>';echo 'Exponent of 1 = ',exp(2),'<br>';
97echo 'pi() = ',pi(),'<br>';echo 'ceil value = ',ceil(2.1111),'<br>';echo 'Floor Value = ',floor(2.9999),'<br>';echo 'round = ',round(2.51458),'<br>';echo 'round = ',round(2.51558,2),'<br>';echo 'rad2deg(M_PI) = ',rad2deg(M_PI),'<br>';echo 'rad2deg(M_PI) = ',rad2deg(M_PI_2),'<br>';echo 'rad2deg(M_PI) = ',rad2deg(M_PI_4),'<br>';echo 'deg2rad = ',deg2rad(180),'<br>';echo 'sin 90 = ',sin(M_PI_2),'<br>';echo 'tan 45 = ',tan(M_PI_4),'<br>';echo 'hypot value = ',hypot(3,4),'<br>';echo 'rand(min,max) = ',rand(100,1000),'<br>';echo 'min value = ',min(10,20,30),'<br>';echo 'max Value = ',max(2.999,2.998),'<br>';?>b)Date & Time Functions :Date : date is the pre-defined constant in php. It will generate currentdate according to the number of arguments passed.Mktime : Which can have arguments (hr, min, sec, month, day, year)unique time stamp.Check date() : Let us known the validate in a yearj----> represents day of the month without leading zerosl---->view letter represents of the day of the wayL---> whether it’s a leap year (or) not
98W---> week number of year weeks starts from Mondayw----> numerical represents of day of the way 0 for Monday through6 for SaturdayS---> English original safix for the day of the month two character ex:-st ,nd, rd,thF----> a full representation of the month such as January (or) MarchM---> short representation of the month such as jan (or) marm---> numerical representation of the month with leading zero’smeans 0-12n---> numerical representation of month without zero’s which is 1-12d---> number of days given in a month 28 (or) 31y---> two digits representation of a yearY---> it is representation of the full yearTime : Number of milliseconds sec right from unique time stampa---> lowercase ante meridiem and post meridiemA---> uppercase ante meridiem and post meridiemB---> swatch internet timeg---> 12- hours format of an hour without leading zerosG---> 24- hour format of an hour without leading zerosh---> 12- hours format of an hour with leading zerosH--->24- hours format of an hour with leading zerosi---> minutes with leading zero’ss---> seconds with leading zero’su---> microseconds (added in php 5.2.2)
99Ex :<?phpecho 'Time zone set to : ',@date_default_timezone_get(),'<br>';date_default_timezone_set('America/Denver');echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';echo 'Today Date : ',@date("M-dS-Y, h:i:s a"),'<br><hr>';date_default_timezone_set('America/Los_Angeles');echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';echo 'Today Date : ',@date("M-dS-Y, h:i:s a"),'<br><hr>';date_default_timezone_set('Asia/Calcutta');echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';echo 'Today Date : ',@date("M-dS-Y, h:i:s A"),'<br><hr>';var_dump(checkdate(02,29,1975));echo '<hr>No of milliseconds from Unix time Constant ',time(),'<br>';echo '<hr>Feature Date & time <br>';echo 'Event is on : ',(date("M-dS-Y, h:i:sa",mktime(7,9,52,8,23,2012))),'<br><hr>';echo date('Y');?>c)Array built-in Functions :<?php$a = array(10,20,30);function r($arr,$func=''){if(!empty($func)){
100echo "<h2 align='center'><u>$func</u></h2>";}foreach($arr as $k=>$v){echo "$k = $v<br>";}echo '<hr>';}echo 'Array count = ',count($a),'<br>';echo 'Size of = ',sizeof($a),'<br>';echo 'Sum of Array = ',array_sum($a),'<br>';echo 'Product of Array = ',array_product($a),'<br>';$a =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');r($a,'Normal Array');$b = array_change_key_case($a,CASE_UPPER);r($b,'Upper Case');$b = array_change_key_case($a,CASE_LOWER);r($b,'Lower Case');$b = array_flip($a);r($b,'Array Flip');$b = array_change_key_case(array_flip($a),CASE_UPPER);r($b,'Array Flip Values');$a = array('Doctor','Fruit','Software');$b = array('Patient','Orange','PHP');
101r(array_combine($a,$b),'Array Combine');$a =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');echo '<h2 align="center">Array Chunk</h2>';$b = array_chunk($a,3);echo '<pre>';print_r($b);echo '</pre>';$a = array(10,20,30);$b = array(10,20,40,50);r(array_merge($a,$b),'Array Merge');r(array_intersect($a,$b),'Array Intersect');r(array_diff($a,$b),'Array Diff');$a =array('raj@gmail.com','amith@gmail.com','rohan@gmail.com','sumit@gmail.com','raj@gmail.com');r(array_unique($a),'Array Unique');r(array_reverse($a),'Array Reverse');$a = array(10,20,30);array_unshift($a,5);r($a,'Unshift Method');array_shift($a);r($a,'shift Method');array_push($a,40);r($a,'Push Method');
102array_pop($a);r($a,'Pop Method');$ns = $ss = $as = $ks =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');r($ns,'Normal Array');sort($ss);r($ss,'Sorted Array');rsort($ss);r($ss,'Reverse Sort Array');asort($as);r($as,'Associative Sort Array');arsort($as);r($as,'Associative Reverse Sort Array');ksort($ks);r($ks,'Key Sort Method');krsort($ks);r($ks,'Key Sort Reverse Method');echo "<h2 align='center'>array_key_exists , array_search ,in_array</h2>";$a =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');echo 'Do i have Email Feild :',var_dump(array_key_exists('Gender',$a)),'<br>';echo 'Do we have Value with some :',var_dump(array_search(30,$a)),'<br>';
103echo 'Do we have Value with some :',var_dump(in_array('Male',$a)),'<br>';$a =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');r(array_keys($a),'Array Keys Calling');r(array_values($a),'Array Value Calling');$str = 'Hey i am from India & my name is Praveen';$b = explode(" ",$str);//print_r($b);echo '<br>';echo 'The Length of your total Words = ',count($b),'<br><hr>';for($i=0;$i<count($b);$i++){echo 'The index at ',$i,' = ',$b[$i],'<br>';}$a =array('raj@gmail.com','amith@gmail.com','raju@gmail.com','suresh@gmail.com','raj@gmail.com','amith@gmail.com','raju@gmail.com','suresh@gmail.com');print_r($a);$b = implode(',',$a);<br><br>To : <input type='text' name='name' value='<?php echo $b;?>'size='60'/><hr><?php$a = array('born','child','teen','father','dead');r($a,'Normal Array');
104echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'Next : ',next($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'Previous location : ',prev($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'End Value : ',end($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'Reset ',reset($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<hr>';$a = array('Name'=>'Rajesh','Age'=>30);r(Each($a),'Each Method');r(Each($a),'Each Method');$a = array('ram','processor','computer');list($gb,$intel,$dell) = $a;echo "$gb & $intel together makes $dell faster<br><hr>";$str = "write some large text matter.";echo $str,'<br><hr>';echo '<h2>Wordwrap</h2>';echo wordwrap($str,20,'<br>',true);?>
105d)String built-in Functions :<?phpecho '<h2>';$str = "lamp institute";echo "Normal String = ",$str,'<br>';echo "Length of String = ",strlen($str),'<br>';echo "To Upper Case = ",strtoUpper($str),'<br>';echo "To Lower Case = ",strtoLower($str),'<br>';echo "Upper case First Word = ",ucfirst($str),'<br>';echo "Upper case words = ",ucwords($str),'<br>';echo 'Reverse = ',strrev($str),'<br>';echo '<hr>';echo 'Position of str = ',strpos($str,'t'),'<br>';echo 'last Position of str = ',strrpos($str,'t'),'<br>';echo 'Postion of str after t again = ',strpos($str,'t',9),'<br>';echo 'Position insensitive = ',stripos($str,'lamp'),'<br>';echo 'last position at t insensitive = ',strripos($str,'T'),'<br>';echo 'strstr will extract the entire string : ',strstr($str,"In"),'<br>';echo 'strstr will extract the entire string : ',stristr($str,"in"),'<br>';$name = 'Rajesh Kumar';echo "substr = ",substr($name,0),'<br>';echo "substr = ",substr($name,7,4),'<br>';echo "substr = ",substr($name,-5,-1),'<br>';$url = 'http://www.google.com?status=active';
106$url .= '&';echo 'substr = ',substr($url,0,-1),'<br>';echo 'replace = ',str_ireplace('lamp','Apache',$str),'<br>';$a ='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';echo str_shuffle($a),'<hr>';echo substr(str_shuffle($a),0,12);echo '<hr>';$name = "O'henry";echo $name,'<br>';echo addslashes($name),'<br>';echo stripslashes('O'henry'),'<br>';echo strip_tags("<b><i>Hi i am not feeling well</i></b>");echo '<hr>';echo '<h2>';$pwd = 'computer';echo 'Original Name : ',$pwd,'<br>';echo '<h1 align="center">One Way Encrypt</h1>';echo 'Encrypt with MD5 = ',md5($pwd),'<br>';//32 char valueecho 'Encrypt with MD5 strict = ',md5($pwd,true),'<br>';//16 bitbinary formatecho 'Encrypt with sha1 = ',sha1($pwd),'<br>';//40 char vlaueecho 'Encrypt with sha1 strict= ',sha1($pwd,true),'<br>';//20 binaryvlaueecho 'Crypt = ',crypt($pwd),'<br>';echo 'crypt salt = ',crypt($pwd,'d4'),'<br>';
107echo '<h1 align="center">Encrypt & Decrypt Method</h1>';echo 'encrypt = ',base64_encode($pwd),'<br>';echo 'decrypt = ',base64_decode('Y29tcHV0ZXI='),'<br>';echo '<h1 align="center">Url Encode & Decode</h1>';$url = 'http://www.lamp.com?status=success&id=7&pid=20';echo 'Original url = ',$url,'<br>';echo 'encode = ',urlencode($url),'<br>';echo 'decode =',urldecode('http%3A%2F%2Fwww.lamp.com%3Fstatus%3Dsuccess%26id%3D7%26pid%3D20'),'<br><hr>';echo '<pre>';$name = " Rajesh ";echo 'My name is :',$name,'<br>';echo 'My name is :',rtrim($name),'<br>';echo 'My name is :',ltrim($name),'<br>';echo 'My name is :',trim($name),'<br>';echo '</pre>';?>PATH :FILE : The full path and filename of the file. If used inside aninclude, always contains an absolute path with some linksLINE : The current line number of the file.DIR : The directory of the file.Realpath : Returns absolute pathnameBasename : Returns filename component of path
108Ex :<?phpecho "File Information : ",__FILE__,'<br>';echo "Base Name : ",basename(__FILE__),'<br>';echo "Directory Name : ",dirname(__FILE__),'<br>';echo "Directory Name : ",__dir__,'<br>';echo "real Path : ",realpath(__FILE__),'<br>';//echo "real Path : ",realpath('../..'),'<br>';echo "Line NO : ",__LINE__,'<br>';echo '<hr>';$a = pathinfo(__FILE__);//print_r($a);foreach($a as $k=>$v){echo $k,' = ',$v,'<br>';}?>e)File Functions :1) stat(file path) : This function Return an array with file information2)is_file(file path) : Checks wheather the file exist or not & ReturnsBoolean value.3)file_get_contents(file Path) : Returns the file content as a string.4)file_put_contents(fiel path,data) : Writes the content to the fileoverwriting old content and if file does not exists, creates a new file &adds the content.This function is introduced in 5th version.
1095)file(file path) : Returns the file content as an array with each line inthe file at a particular index position.6)filectime(path) : Creates the time of the file.7)fileatime(file path) : Last access time of the path file.8)filemtime(file path) : Last modified time of the file.9)unlink(file path) : Removes the file from the location.10)filesize(file path) : Returns the size of the file in bites11)filetype(file Path) : Returns the type of the file (dir or file)12)fopen(file path,mode) : Opens the file in the specified mode andreturns a file handler for handling the file.13)fread(file handler, size) : Reads the file content from the currentfile handler position upto the specified size.14)$fp -> file Pointer ..The internal handler which is used forhandling the file.15)fgetc(file handler) : Reads a single char in the string.16)fgets(file handler) : Reads a single line from the file..17)fgetss(file handler) : Reads a single line from the file stripping ofhtml tags in the file.18)fwrite(file handler) : This function is used to write the content tothe file19)ftell(file handler) : Returns the file handler position in the file20)fseek(file handler) : Moves the file handler to the specifiedposition in the file21)fclose(file handler) : Closes the File handler connection.List of Modes :r --> Read Moder+ --> Read and Write.
110w --> Write Modew+ --> Write & Read.a --> Append (also writing but without overwriting files)a+ --> append & read.x --> Creates a new file & write..x+ --> Creat a new file for write and read.rb,rb+,wb,wb+,ab,ab+,xb,xb+ are the modes to be used for binaryfiles.Examples for above specified actions :-----fileput.php<?php$file = 'a.txt';file_put_contents($file,str_repeat("MOd ",5));?>-----create.php<?php$file = 'c.txt';$fp = fopen($file,"x");fwrite($fp," Created");fclose($fp);if(is_file($file)){echo file_get_contents($file);}?>
111-----write.php<?php$file = 'b.txt';$fp = fopen($file,"w");fwrite($fp,"Modified");fclose($fp);if(is_file($file)){echo file_get_contents($file);}?>-----read.php<?php$file = 'test.txt';$fp = fopen($file,"r");echo "Pos : ",ftell($fp),'<br>';echo fread($fp,3),'<br>';echo "Pos : ",ftell($fp),'<br>';echo fgetc($fp),'<br>';echo "Pos : ",ftell($fp),'<br>';echo fgets($fp),'<br>';echo fgets($fp),'<br>';echo 'Pos : ',ftell($fp),'<Br>';echo fgets($fp),'<br>';fseek($fp,35);
112echo fgetss($fp),'<br>';fclose($fp);?>-----func.php<?php$file = 'test.txt';var_dump(is_file($file));echo '<br>';echo "size : ",filesize($file),'<br>';echo "Type : ",filetype($file),'<br>';echo "Created : ",date("d-m-y h:i:s",filectime($file)),'<br>';echo "Accessed : ",date("d-m-y h:i:s",fileatime($file)),'<br>';echo "Modified : ",date("d-m-y h:i:s",filemtime($file)),'<br>';echo file_get_contents($file),'<br>';echo "<pre>";print_r(file($file));echo '<br>';print_r(stat($file));?>-----append.php<?php$file = 'b.txt';$fp = fopen($file,"a");fwrite($fp,"Append");
113fclose($fp);if(is_file($file)){echo file_get_contents($file);}?>-----unlink.php<?php$file = 'a.txt';unlink($file);?>f)Directory Functions:1)getcwd() : Current working directory,2)chdir(path) : Change current working dir to argumented path.3)is_dir(path) : Checks wheather the argumented dir exist or not andreturn Boolean value.4)mkdir(dirname) : Makes a directory on the current workinglocation.5)rename(old name,new name): Changes the name of the directory.6)rmdir(dir name) : Removes the directory.7)scandir(path) : Scan the directory and return the directory contentas an array. Returns an array with related path information.-----getcwd.php<?phpecho 'Cwd : ',getcwd(),'<br>';$a = scandir('.',0);
114foreach($a as $k=>$v){echo "$k == $v<br>";}chdir('..');echo '<hr>';echo 'Cwd : ',getcwd(),'<br><hr>';$a = scandir('.',0);foreach($a as $k=>$v){echo "$k == $v<br>";}?>-----mkdir.php<?php$dir = 'test';if(!is_dir($dir)){mkdir($dir);echo "Directory is created";} else {echo "Directory already exists";}?>-----rename.php<?php$dir = 'test';$new = "modified";
115if(is_dir($dir)){rename($dir,$new);echo "Directory name is $new";}else {echo "Directory does not exists";}?>-----rmdir.php<?php$new = "modified";if(is_dir($new)){rmdir($new);echo "Directory is removed";}else {echo "Directory does not exists";}?>scandir.php<?phpecho '<pre>';var_dump(scandir('.'));?>
116Super Globals :Difference between GET and POST :GET POST1.GET data transfers through URL. POST data is sendthrough request headers2.GET is insecure POST is secure3.File cannot be transfered using GET Files can betransfered4.Limited data can be send based on length We can send hugedata(8MB) which can be scaledof URL supported by browser(2KB). up by usingPOST_MAX_SIZE5.It is fast It is not as fast as GET.6.$_GET is used for accessing $_POST is used for accessingthe GET parameters the POST parametersGET Ex :-----get.php<?phpif(isset($_GET['submit'])){echo 'Name : ',$_GET['fname'],'<br>';echo 'Email Address : ',$_GET['email'],'<br>';$gend = ($_GET['gender'] == 'm')?'Male':'Female';echo 'Gender : ',$gend,'<br>';}
117echo '<hr>';echo urldecode($_SERVER['QUERY_STRING']);echo '<hr><br>';?>-----get.html<form method='GET' action='get.php'>Name : <input type='text' name='fname' value=''><br>E-Mail : <input type='text' name='email' value=''><br>Gender : <input type='radio' name='gender' value='m'> Male <inputtype='radio' name='gender' value='f'> Female<br><input type='submit' name='submit' value='Register !'></form>POST Ex :-----post.php<?phpif(isset($_POST['submit'])){echo 'Name : ',$_POST['fname'],'<br>';echo 'Email Address : ',$_POST['email'],'<br>';$gend = ($_POST['gender']=='m')?'Male':'Female';echo 'Gender : ',$gend,'<br>';$a = $_POST['course'];echo $a,'<br><hr>';print_r($a);}echo '<hr>';echo 'The query string : ',$_SERVER['QUERY_STRING'],'<br>';
118?>-----post.html<form method='POST' action='post.php'/>Name : <input type='text' name='fname' value=''/><br>E-Mail : <input type='text' name='email' value=''/><br>Gender : <input type='radio' name='gender' value='m'/> Male <inputtype='radio' name='gender' value='f'/> Female <br>Hobbies : <br><input type='checkbox' name='course[]' value='c'/> C-Language <br><input type='checkbox' name='course[]' value='p'/> PHP <br><input type='checkbox' name='course[]' value='j'/> Java <br><input type='submit' name='submit' value='Register'/></form>Server Variables :-----servervariables.php<?phpecho 'Get Environment : ',getenv('os'),'<br>';echo 'Environment Path : ',getenv('path'),'<br>';echo '<hr>';echo 'Document Root : ',$_SERVER['DOCUMENT_ROOT'],'<br>';echo 'Http Host : ',$_SERVER['HTTP_HOST'],'<br>';echo 'Referer : ',$_SERVER['HTTP_REFERER'],'<br>';echo 'Method : ',$_SERVER['REQUEST_METHOD'],'<br>';echo 'User Agent : ',($_SERVER['HTTP_USER_AGENT']),'<br>';
119echo 'Name of Script : ',$_SERVER['SCRIPT_NAME'],'<br>';echo 'Query String : ',$_SERVER['QUERY_STRING'],'<br>';echo 'Remote Ip Address : ',$_SERVER['REMOTE_ADDR'],'<br>';echo 'PHP Self : ',$_SERVER['PHP_SELF'],'<br>';echo 'Request URL : ',$_SERVER['REQUEST_URI'],'<br>';echo 'Script File Name : ',$_SERVER['SCRIPT_FILENAME'],'<br>';?>-----phpinfo.php<?phpecho phpinfo();?> Include_once and required _once : These both will include filevery first time and if already file has been included this will notinclude for the second time. Defference between include_once & include : Include andinclude _once will include the files. But if the path of the file is wronginclude and include_once will generate the wrong message and rest ofthe code will be excuted.Required and required_once : If location of the path is givenwrong this will through a wrong as well as path error and code getshalted or the execution will be stop.Ex : a.php<style>b{color:green;}</style><b>I am included</b><br><hr><?php
120$a = 10;if(!function_exists('r')){function r(){echo 'I am in a.php and working fine<br>';}}?>b.php<?phpinclude_once("a.php");include("a.php");include("a.php");$b = 20;echo 'The Value of $a = ',$a,'<br>';echo 'The Value of $b = ',$b,'<br>';r();?>Headers :Headers are the information which are exchanged between client andserver for every request and response.Headers are of two types.a) Request Headers.b) Response Headers.a) Request Headers : These are send from client to server.
121HTTP Request : GET/php7/info.php HTTP/1.1Host : localhostUser_Agent : Mozilla/5.0Accept : text/HTML, application/htmlAccept_encoding: gzip,deflateConnection : keep-alivekeep-alive : 115Accept_char : ISO-88591-1 utf-8;q=0.7Ex : apache_request_headers()b) Response Headers : These are send from server to client.X-powered-by : php/5.3.1keep_Alive : timeout=5,max=100connection : Keep_AliveTransfer_Encoding : chuntedcontent_type : text/htmlEx : apache_response_headers()HTTP Methods :For every request from the client to server can be made throughvarious HTTP methods likeGET, POST, PUT, DELETE, HEADHeaders can be send from php program to the server.1. headers_list() : Returns an array to the list of the headers whichcan be shared from server to client.
1222. headers_sent() : Returns the boolean value above whether theheaders were send to the client or not.3.header("<name>:<value>") : Header function should be used inthe page before any output is send to the page.Header functions are used for redirection and for sending the outputand also for downloading of the files.Php content in different formats(content type likehtml,xhtml,images,pdf,flash,video etc).Ex :-----hrds.php<?phpob_start();print_r(apache_request_headers()); echo '<hr>';var_dump(headers_sent());header("Name:Rajesh");header("location:info.php");print_r(headers_list());echo '<hr>';print_r(apache_response_headers());?>-----info.php<?phpecho phpinfo();?>
123Downloading :Step 1: Download of a file is done by sending few headers followedwith reading of source file from the server sending a content typeheader.header("Content-Type:<mine Type>");pdf -> application/pdf.html -> text/html.jpg/png/gif -> image/(jpg || png || gif).Step 2: Sending a content Disposition header which will tells thebrowser to open the file or to ask the user about the file.header("Content-Disposition:<mode>;filename=<filename>");----->Inline----->attachmentStep 3: Optionally we can sent content length header with the size ofthe file.header("Content-Length:<filesize(finename)>");Reading the Original file :readfile(<path of file>)  Reads the file Content and prints to thebrowser.Ex : download.php<?php$file="01.jpg";$type="image/jpg";$mode="inline";header("Content-Type:".$type);header("Content-Disposition:".$mode.";filename=".$file);header("Content-Length:".filesize($file));
124readfile($file);?>----down.phpmage down <a href="download.php"/>View Please</a>File Uploading :upload_tmp_dir(<path>) : default is set to c:xampptmp. Thetemporary location to which the file can be uploaded to the server.upload_max_filesize : (<128>) The max size for a single file whichcan be uploaded to the server -> max_file_uploads : 20.Functions in upload :copy of source destination : Copy the file from source location todestination folderis_upload_file(source path): Checks wheather file upload or notand return boolean.move_upload_file (<source path, destination>): Moves the filefrom source location to destination locationPredefined variables: - $_FILES is predefined super global filewhich will be loaded with theProperties in file upload :1. $_FILES[<file_field_name>]['name']: It returns the originalname of the uploaded file.2. $_FILES[<file_field_name>]['tmp_name']: It returns thetemporary path to the uploaded file.(It acts as the source path of the uploaded file in the program).3. $_FILES[<file_field_name>]['size']: It returns the size of theuploaded file in bytes.4. $_FILES[<file_field_name>]['type']: It gives the MIME(Multipurpose Internet Main Extension) type for the uploaded file.
1255. $_FILES[<file_field_name>]['error']: It returns the error codeassociated with the file upload.If its value is configured to zero indicates no error.Ex : testupload.php<?phpif(isset($_POST['submit'])){if(isset($_FILES['photo'])){$src = $_FILES['photo']['tmp_name'];$desc ="pics/".getRandString(12).$_FILES['photo']['name'];if(move_uploaded_file($src,$desc)){echo 'Image saved successfully<br>';} else {echo 'Image not saved<br>';}}}echo '<hr>';function getRandString($size){$a =str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');return addslashes(substr($a,0,$size));}?>
126-----test.php<form action='testupload.php' method='POST'enctype='multipart/form-data'/>Upload Photo : <input type='file' name='photo'/> <input type='submit'name='submit' value='Upload'/></form>COOKIES :Cookies are super global variables which can be stored at clientmachine.$_COOKIE: It is a predefined super global variable which can beused for reading cookie data.setcookie(<name>,<value>): It is a predefined function for creating,updating or deleting the cookie variable at server machine.cookie values are stored at the browser of client's machinecookies are not safe for storing the information.Every webbrowser is limited to a certain number of cookies to bestored at the client's machine(~20).Cookies information will be exchanged between the client and serverevery request and response through headers.If Cookie is once created can be accessed from the next request fromthe server to the client but not in the same page.setcookie(<name>,<value>,[<lifetime>],[<domain>],[<path>],[<secure protocol>])lifetime: Timestamp upto which cookie must be active.time()+24*60*60domain: news.abc.comgmail.com
127path: Default path is current working directory/  Points to root directory/abc  Cookie is shared with all files in abc foldersecure_protocol: If it is true then it will be exchanged with httpsprotocol otherwise with http protocolCookie can be created in two ways.1. By creating cookie with empty value.2. By creating the cookie in the pastEx : create.php<?phpob_start();print_r($_COOKIE);setcookie('c',10,time()+3600);//set cookieecho "<br>";print_r($_COOKIE);setcookie('c',88,time()+3600);//modify or updateecho "<br>";setcookie('c',"",time()+3600);//deleteecho "<br>";setcookie('c',"abc",time()-3600);//deleteecho "<br>";?>setcookie will sends a header to the server(No output is sent beforeusing.)If output is started before it use output buffering.
128SESSIONS :It is used for maintaining the state of the user between his login andlogout. Session information is stored at the server machine and isaccessable with the pages where session is started.$_SESSION is a predefined super global used for managing sessiondata.Configuration Settings:session.auto_start(OFF) : Controls whether the session must beautomatically started or not.session.name=PHPSESSID: The default name at which session id isstored at a client machine as cookie variable.session.use_cookie(ON*/OFF): Using the cookies for storing thesession id value.session.use_only_cookies: Using cookies only for storing the sessionid.session.use_trans_sid(0/1): Using a transferable session id throughURL.session.gc_maxlifetime(1440(24minutes)): The maximum time forwhich the session data can be maintaines when the user is idle beforesending to gc(garbage collector).Functions in SESSIONS :session_start(): Starts a new session for the user, if session alreadyaxists uses the already existing session.session_name[<optional_name>]: Gets or sets the name of thesession.session_id(): It returns the session id created for the user. A sessionid is a unique 32 character length alphanumeric value.session_regenerate_id : Changes the session id to new one for theuser.
129session_unset: Erases the session data for the user.session_destroy: Session will be destroyed.Ex : session.php<?phpob_start();session_start();echo 'Session Name : ',session_name(),'<br>';echo 'Session Id : ',session_id(),'<br>';echo 'Session Name : ',session_name('Rajesh'),'<br>';echo 'Session Name : ',session_name(),'<br>';echo 'Session generate Id : ',session_regenerate_id(),'<br>';echo 'Generated Id : ',session_id(),'<br>';echo 'Life time : ',(ini_get('session.gc_maxlifetime')/60),' mins<br>';echo 'Session save Path : ',ini_get('session.save_path'),'<br>';echo 'Cookie Save Path : ',ini_get('session.cookie_path'),'<br>';$_SESSION['Name'] = 'Praveen';$_SESSION['Email'] = 'raj@gmail.com';print_r($_SESSION); echo '<hr>';print_r($_COOKIE);echo '<hr>';session_destroy();echo 'Session Id : ',session_id(),'<br>';print_r($_SESSION);unset($_SESSION['Name']);echo '<hr>';print_r($_SESSION);
130echo '<hr>';print_r($_COOKIE);?>Global Configuration Settings :Understanding Configuration settings in PHP:1) POST_MAX_SIZE : Max size of post data that a php will accept2) magic_quotes_gpe : Escaping of " Quotations with a backslash forthe data which is sent through GET,POST,COOKIE & ENVvariables.Default value is set to ON.3) Register_globals : Possible values are ON and OFF. By default isOFF. Registering of super global variable as regular variables in thispage is controlled with this settings4) variables_order : "GPCS";The order which superglobal variableare loaded with the current working page5) Register_long_arrays : ON or OFFThe availability of superglobals array with login array names used inthe older version of PHP is controlled with this settings.6) file_uploads: ( ON) whether to allow HTTP Files to upload or not;Buffer :Buffering of the output before sending with browser can be handledby using output buffering.Configuration settings :Output_buffering = 4096Buffers the output upto 4KB and releases the output.Functions :ob_start() : Starts the buffering output if buffering is inactive.
131ob_get_length : It returns the size of buffer content in the pageob_flush() : It sends the buffer content to the browser.ob_get_flush() : It returns the buffer content as a string and sends thebuffer to the browser.ob_clean() : It clears the buffer and stops the buffering.ob_get_clean : It cleans the buffer content and returns it as a string.Note : Output buffering is used when we are working with sessionsusing headers with in the page.Ex : buffer.php<?phpob_start();echo 'Line 01<br>';echo 'Line 02<br>';echo ob_flush(); //implicit_flush = Off;header("Name:Rajesh");//echo ob_get_length();echo '<hr>';echo ob_get_contents();?>
132
133MySQLMySQL is a Open Source database server which is developed on topof C & C++ Languages.MySQL supports many programming & Scripting languages forproviding access to the data like C,C++,Java,.Net,PHP,PERL,Pythonetc..MySQL was initially developed by MySQL-AB Group of sweaden,which was merge with Sun Microsoft system in Aug 8th, 2008..MySQL Supports ANS Based SQL FOR Communicating withdatabase server MySQL will allow the SQL statement to get executedthrough various channel like.1) GUI Tools(Graphic user Interface),MySQL Administrator,SQLyog, SQL etc2) Web Based Tools(phpmyadmin, SQL ETC...)3) Command Line Interface : Accessing local database Server Locally4) Data : This is collection of informationDatabase : It is a collection of DataDBMS :DBMS stands for Data Base Management System.It Suggests theinternal Organization in Database Server.DBMS is used for defining Structural architecture of data base andinternal organization of the data in Various types of DBMS.1)HDBMS (Hierarchical Data Base Management System)2)NDBMS (Network Data Base Management System)3)RDBMS (Relational Data Base Management System)4)ODBMS (Object Data Base Management System)
1345)ORDBMS(Object Based Relational Data Base ManagementSystem)RDBMS :In RDBMS db is considered as a collection of tables, each table is acollection of records, and each record consists of collection of data set(cols,rows).E.F.CODD : 12 Rules of RDBMS..can be found at(http://www.cse.ohio-state.edu/~sgomori/570/coddsrules.html)Normalization :5 Forms(1st three has to understood);SQL : Structural Query Language which is used for Communicatingwith data base Server.Database Server : It is a Software which will receive the request inSQL and sends the data as the response.Eg: MySQL,Oracle,Sybase,Postgre SQL,DB2,MSSQL,MS AXISetc..SQL:a)DDL(Data Defination Language)CREATE -------------|---> Database|  Table||DROP ---------------|---> Database|  Table|ALTER---------------|--->Used for Tables
135|  ADD|  CHANGE|  DROPTRUNCATE------------|--->TABLEb)DML (Data Manipulation Language)|  INSERT INTO|  UPDATE SET|  DELETE FROMc)DRL (Data Retrivel Language)|  SELECT |  WHERE <cond>|  ORDERED BY <field-Name>|  GROUP BY <field-Name>|  LIMIT <start>,<end>d)DCL (Data Controlling Language)|  ADMIN ZONEe)TCL (Transaction Control Language)|  Giving Special Permission.Data Base LevelQuery :SHOW DATABASES  Return the List of DatabasesCREATE DATABASE  <db_name> Creates a database if it is notExisting.a)USE <db_name>  Select a database for executing further Queriesin the Table.b)DROP DATABASE<db_name>  Deletes the database from thedatabase server Completely with its Tables and data.
136Table Level Query : SHOW TABLES[FROM <db_name>]; CREATE TABLE <table_name> (<field_name><datatype>[<size>] <add_parementers> <field_info); ALTER TABLE <table_name> ADD <field_info>; CHANGE <field_name> <new_field_info>;ALTER TABLE <table_name> DROP <field_name>;RENAME <new_name>;(Renaming a Table) TRUNCATE <table_name>;This will empty the table. Removes the complete data ofthe table but the structure of table remains same in the database. DROP<table_name>; Removes the table data and its Structure;Data Level Query :Data manupulation Language:INSERT INTO <tbl_name> [(<field_list>)] VALUES[(<value_list>),(<value_list2),(value_list3)...]; UPDATE <tbl_name> SET <field_name> = <new_value>WHERE <cond>; DELETE FROM <tbl_name> WHERE <cond>;Data Retrival Query: SELECT (* or <field_list>) FROM <tbl_name> [WHERE<cond>] ORDER BY <field_name> ASC/DESC [GROUP BY<field_name> LIMIT <start_index>[,<length>]];Numerical Datatypes in MYSQL :1) Tiny Int : [2pow8 -1] 0-255  UNSIGNED[-128-127] SIGNED
1372) Small Int : 2 bytes [2pow16-1]  UNSIGNED-32767 TO -32767  SIGNED3) Mediun Int : 3 bytes [2pow24-1]UNSIGNED int [16777215]SIGNED int [-8388607]4) Int : 4 bytes [2pow31-1]SIGNED Int Range [2147483647]5) BigInt : 8 bytes [2pow64-1]0 - 1.84467440737096e+14 20digitsSize of integer will specify the total number of digitsAdditional Parameter SIGNED OR UNSIGNED default Value isSIGNED.6) float(<no of digits>,<precision>) :A small number with a floating Value .10POW38 0-24(falls in float)7) Double(no of digits>,<precision>) :A Large Number with a floating Decimal Point(25-5)8) Decimal() : A double stored as a string, allowing for a fixeddecimal point.9) Char() : A fixed Section from 0 to 255 character Long.10) varchar() : A variable section from 0-255 char long.Miscellaneous Types :ENUM() : ENUM stands for Enumeration, which means that eachcoloumn may have one of a specified possible Value.Text : String Content 65kb for this size is needed.medium text : 0 - 16777215 char (16mb) can be accomidated inmedium text..
138long text : 0 to upto 4gb long textENUM :ENUM is a Miscellaneous datatype . Enumeration field used forstoring Optional values among which one value can be selected whileinserting (0-65535) maximum number of optiona, which are allowedall string values must be enclosed in "Quotations" while inserting.Date Data types :Date : YYYY-MM-DD(0000-9999)allowed datesTime : hh:mm:ssDate & Time : YYY-MM-DD hh:mm:ssTIME STAMP : Defaultly insert the current date and time values.yyyymmdd hhmmss  14yyyymmdd hhmm  12yymmddhhmm  10yyyymmdd  8yymmdd  6Year : 4-digits Year number ,all date values must be enclosed inQuotations during the insertion.Binary Data Types :Binary : Fixed length binary content (similar to char)Var binary : it is variable length binary content similar to varchar.Blob : binary Large Object similar to text data typeMedium Blob : Similar to medium Text.Long Blob : similar to Long Text.
139Additional Parameters :1) PRIMARY KEY : Atleast one field in a table must be declared asprimary key, it is UNIQUE it is by default an INDEX for the table. itcan't be NULL.2) FOREIGN KEY: The field which establish a relation to theprimary key field of the table is foreign Key.3) UNIQUE : The field apart from primary Key which needs to beUNIQUE can be applied with this field..4)CURRENT_TIMESTAMP : Predefined constant which can storecurrent time stamp value by default at the time of inserting the date ortime. On update current-time stamp it is used for adding current timestamp at the time of updation.5) AUTO_INCREMENT : Increase the value by one automaticallyfor every row record entry. CreateCREATE TABLE eg_user(Id SMALLINT(5) UNSIGNED NOTNULL PRIMARY KEY AUTO_INCREMENT, EmailIdVARCHAR(100) NOT NULL UNIQUE, Pword CHAR(32) NOTNULL, Gender ENUM('Male', 'Female') NOT NULL,DateOfBirthDATE NOT NULL,RegisteredOn TIMESTAMP DEFAULTCURRENT_TIMESTAMP, uStatus ENUM('Inactive', 'Active') NOTNULL);DESC eg_user;DESCRIBE eg_user;EXPLAIN eg_user; Inserting recordsINSERT INTO eg_user (EmailId, Pword, Gender, DateOfBirth)VALUES ('mra@xyz.com', MD5('abc'), 'Male', '12-12-1980');
140 List all records of tableSELECT * FROM table_name;Inserting multiple recordsINSERT INTO eg_user (EmailId, Pword, DateOfBirth, Gender)VALUES ('mrb@xyz.com', MD5('1'), '1979-10-19','Male'),('msc@xyz.com',MD5('a'), '1980-5-12','Female'),('mrd@xyz.com',MD5('ab'), '1972-6-10','Male'),('mse@xyz.com',MD5('AB'), '1989-12-12','Female'); Modifying the recordUPDATE eg_user SET DateOfBirth='1980-12-8', uStatus='Active'WHERE Id=1;Deleting the recordDELETE FROM eg_user WHERE Id=5;TRUNCATE TABLE tbl_name;Example : Create emp tableCREATE TABLE eg_emp(Id SMALLINT(5) UNSIGNED PRIMARY KEYAUTO_INCREMENT,Name VARCHAR(30) NOT NULL,Salary DECIMAL(10,2) NOT NULL,Location VARCHAR(50) NOT NULL) AUTO_INCREMENT=101;Inserting RecordsINSERT INTO eg_emp (Name, Salary, Location) VALUES('Mr.A',5000, 'Hyd'),('Mr. B', 4500, 'Mumbai'), ('Ms. C', 6000,'Delhi'),('Mr. D', 7000, 'Delhi'),('Mr. B', 5000, 'Hyd'),('Ms. E', 3000, 'Hyd');
141Read records for only specified columns Name, locationSELECT Name, Location FROM eg_emp;List emps with salaries < 5000SELECT * FROM eg_emp WHERE Salary<5000;List emps whose salary is either 3000, 5000, 4000, 7000SELECT * FROM eg_emp WHERE Salary=3000 OR Salary=5000OR Salary=4000 OR Salary=7000;SELECT * FROM eg_emp WHERE SalaryIN(3000,5000,4000,7000);List emps whose salaries are between 5000 & 8000SELECT * FROM eg_emp WHERE Salary>=4500 ANDSalary<=8000;SELECT * FROM eg_emp WHERE Salary BETWEEN 5000 AND8000;List users born between 1-1-1970 and 31-12-1980SELECT EmailId, DateOfBirth, Gender FROM eg_user WHEREDateOfBirth BETWEEN '1970-1-1' AND '1980-12-31';SELECT CURRENT_DATE;SELECT CURRENT_TIME;SELECT MONTH(CURRENT_DATE)SELECT MONTHNAME(CURRENT_DATE);SELECT WEEKDAY(CURRENT_DATE)SELECT DAY(CURRENT_DATE)SELECT DAYNAME(CURRENT_DATE)SELECT EmailId, DateOfBirth FROM eg_user WHERE MONTH(DateOfBirth) = 12;SELECT COUNT(Id) FROM eg_user;
142SELECT SUM(Salary) FROM eg_emp;SELECT SUM(Salary) FROM eg_empWHERE Location='Hyd';SELECT MAX(Salary) AS HighestSalary FROM eg_emp;SELECT MIN(Salary) LeastSalary FROM eg_emp; Number of emps for every locationSELECT COUNT(*) TotalEmps, Location FROM eg_empGROUP BY Location; Number of emps for every location with salary > 4000SELECT COUNT(*) TotalEmps, Location FROM eg_empWHERE Salary>4000GROUP BY Location; List of locations with 2 or more emps having salary>4000SELECT COUNT(*) TotalEmps, Location FROM eg_empWHERE Salary>4000GROUP BY LocationHAVING TotalEmps>1;Salary in descending orderSELECT * FROM eg_empORDER BY Salary DESC;//Salary in desc, with Id descSELECT * FROM eg_empORDER BY Salary DESC,Id DESC;
143List second highest earnerSELECT * FROM eg_empORDER BY Salary DESCLIMIT 1,4; Create Another TableCREATE TABLE brand(Id TINYINT(2) UNSIGNED PRIMARYKEY AUTO_INCREMENT,BrandName VARCHAR(50) NOTNULL);INSERT INTO brand(BrandName) VALUES('Adidas'),('Nike'),('Nokia'),('Titan'),('Lg');CREATE TABLE category(Id TINYINT(2) UNSIGNED PRIMARYKEY AUTO_INCREMENT,Name VARCHAR(50) NOT NULL);INSERT INTO category(Name) VALUES('Mobiles'),('TShirts'),('Jeans'),('Watches'),('Electronics'),('books');CREATE TABLE products(Id SMALLINT(5) UNSIGNEDPRIMARY KEY AUTO_INCREMENT,Name VARCHAR(50) NOTNULL,Amount DECIMAL(10,2) NOT NULL,in_StockTIMESTAMP DEFAULT CURRENT_TIMESTAMP,c_idTINYINT(2) UNSIGNED NOT NULL,b_id TINYINT(2)UNSIGNED NOT NULL);INSERT INTO products(Name,Amount,c_id,b_id) VALUES('Smart watch',612.954,4,4);SELECT * FROM products,category;SELECT p.Name,p.Amount,c.Name FROM products p,category c;SELECT p.Name Products,p.Amount,p.in_Stock,c.Name CategoryFROM products p,category c WHERE p.c_id = c.Id;SELECT p.Name Products,p.Amount,p.in_Stock,c.NameCategory,b.BrandName FROM products p,category c,brand b
144WHERE p.c_id = c.Id AND p.b_id = b.Id ORDER BY AmountDESC;PHP by Default Support With Mysql library,,PHP communication with Mysql can be Splitted int some steps like1) Connecting to the Database2) Selecting to the Database3) Query the Database4) Fetching the Records or Getting the records From Query or QueryString.5) Close the Connection.1) Connecting to the Database Among them We haveA) Normal Connection B) Persistance ConnectionNormal Connection : Will be active for the Single Program, ANormal Connection can be Closed by Using mysql_close();mysql_connect('hostname','username','password');B) Persistance Connection : A Persistance Connection is aPermanent Connection Once establish it cannot be closed.mysql_pconnect('hostname','username','password');2) Selecting to the Databasemysql_select_db('dbname',[Optional Conn Handler]);Selects the Argumented data as current data...Error Handling in Database :a)mysql_error() : Returns the last Error Message Occured with thedata base server.
145b)mysql_errno() : Returns the last error code associated with themysql database Server.3) Querying the Database :a) mysql_query(SQL) : Executes the Query with the database serverand returns the Query Handler.b) mysql_affected_rows : Returns the number of rows affected forthe last insert, Update or delete Query.c) mysql_num_rows(Query handler) : Returns the number ofrecords in the resultant for the select Query .4) Fetching the Records :a) mysql_fetch_row(Query handler) : Returns a single record setfrom the database server, as a numerical array and moves the queryhandler to next record if record does not exist return false.b) mysql_fetch_assoc(Query handler) : Returns the record Set as anassociative array with field names as its index position - if record doesnot exist return false..c) mysql_fetch_array(Query handler) : Returns the record set as anarray with numerical or associative or both arrays . Returns false if norecord found.d) mysql_fetch_object(Query handler) : Returns the record set asan object with field names as its values .5) Close the Connection :a)mysql_close : Close the connection with the data base.There are 2 other functions in php.Which gives a message.if not able to connect to database then we can read the message asdie('Message');die(mysql_errno().' - '.mysql_error()); or exit;
146
147OOPSClass :It is a collection of properties (variables) and methods.Syntax :class <class_name>{//code}[abstract|final] class <class_name>{//code}Property (or) member : A property or member of a class is anidentifier which is used for storing data which can be accessiblethroughout the class.<public|protected| private>[static] <var> =<value>;Ex :public $x=10;protected $account_no=null;static public $conv_rate=0.87;Method :A method is an action for a class (or) a method is a function inside theclass
148Syntax :[static][final|abstract][public*|protected|private] function<fun_name>([args]){//code}Ex :function getName(){return $this->name;}Object :It is an instance of a class.Object is used for accessing classproperties(public). Object can execute methods(public).Syntax :<object>=new <class_name>[args];It is the operator which is used for accessing class propertiesand excuting class methods using an objectEx :<?phpclass A{public $x=20;public function test(){
149echo "Test function<br>";}}$obj=new A;var_dump($obj);echo '$obj->x=',$obj->x,'<br>';$obj->test();$obj->x=21;echo '$obj->x=',$obj->x,'<br>';$obj2=new A;echo '$obj2->x=',$obj2->x,'<br>';?>Constructor :It is a predefined method which is automatically executed within theclass when a class is instantiated. Any argument must be passed tothe class at the time of instatiation.constructor() : It is the predefined name which can be used for theconstructor in a class(php>=5.0). For PHP<5.0 version constructorname must be similar to class name.Ex :<?phpclass Human{public $name="ram";public $age=0;
150function getName(){return $this->name;}function getAge(){return $this->age;}function setName($n){$this->name=$n;}?>$this is a predefined variable which will be instantiated in a classwhen an object is called.$surya=new Human;$surya->name='suryaprakash';$surya->age=32;$juli=new Human;$juli->name='julia robert';$juli->age=45;Destructor (>=PHP 5.0) :The method which will be automatically called when the class objectis uninitialised in the program.destructor() : It is the prereserved name for the destructor.Class constant :const <name>=<value>;
151Ex :const X=10;Class constants are case sensitive. They are suggested to begin withuppercase.Class constants are specific in class, they must be uniquewith in the class.:: (Scope Resolution Operator):It is used for accessing static properties,class constants and Executingstatic methods.Accessing the class constant :Syntax :<class_name>::<constant_name>Self : self is a predefined keyword used for refering the same classwithin the class in scope resolution operator convertion.Parent : parent keyword refers to the parent class.Ex : -<?phpclass Person {private $name;public function __construct($name) {$this->name = $name;}public function getName() {return $this->name;}public function getTitle() {
152return $this->getName()." the person";}public function sayHello() {echo "Hello, I'm ".$this->getTitle()."<br/>";}public function sayGoodbye() {echo "Goodbye from ".self::getTitle()."<br/>";}}class Geek extends Person {public function __construct($name) {parent::__construct($name);}public function getTitle() {return $this->getName()." the geek";}}$geekObj = new Geek("Ludwig");$geekObj->sayHello();$geekObj->sayGoodbye();?>Inheritance :It inherites the properties and methods of a base class to an extendedclass is known as inheritance.
153Base class : A class from which properties and methods are inheritedto child class.Base class can be called as parent class or super class.Extended class or child class or sub class : The class which inheritsthe properties and methods from a base is known as an extended classor child class or sub class.Note : PHP supports multi-level inheritance but won't supportmultiple inheritance.Multilevel inheritance :class A{}class B extends A{}class c extends b{}Multiple inheritances :class X extends Y,Z,W{}//wrongExtends: A predefined key word which is used for inheriting a class.Ex: -class A{public $x=20;
154function test(){echo "test method<br>";}}class B extends a{}$b=new B;echo $b->test();Overriding :Redeclaring a method in the base class with the extended class isknown as overriding.Encapsulation :Hiding of the properties and methods of a class using access specifiers(public,private and protected) is known as Encapsulation.Access Specifiers :These are prereserved keywords which are used for controlling thevisibility of properties and methods.They are public,protected andprivate.Public : A Public property or method which can be accessed orexecuted through the object and method of same class or through themethod of extended class.Protected : A Protected property or method which can be accessedthrough method of same class or extended class(They are notaccessible through object of same class or extended class).
155Private : A Private property or method which can be accessedthrough the method of same class.(It cannot be accessed throughobject of parent or child class and through method of child class).|object of |Method of| Object of | Method of ||same class|same class|extended class |Extended class |---------------------------------------------------------------------------------Public | Yes | Yes | Yes | Yes |---------------------------------------------------------------------------------Protected | No | Yes | No | Yes |---------------------------------------------------------------------------------Private | No | Yes | No | No |---------------------------------------------------------------------------------Ex :<?phpclass A{public $pub="public property<br>";protected $pro="protected property<br>";private $pri="private property<br>";public function pub(){"public Method<br>";}protected function pub(){"protected Method<br>";
156}private function pub(){"private Method<br>";}function accessAll(){echo "<b>Method of same class</b><br>";echo $this->pub;echo $this->pro;echo $this->pri;echo $this->pub();echo $this->pro();echo $this->pri();}}class B extends A{function accessAllB{echo "<hr><b>Method of Extended class</b><br>";echo $this->pub;echo $this->pro;echo $this->pri; //noecho $this->pub();echo $this->pro();
157echo $this->pri();//no}}$a=new A;//Object of same classecho "<b>Object of same class</b><br>";echo $a->pub;echo $this->pro; //noecho $this->pri; //noecho $this->pub();echo $this->pro();//noecho $this->pri();//no$a->accessAll();$b=new B; //Object of extended classecho "<b>Object of extended class</b><br>";echo $b->pub;echo $b->accessAllB();?>Static :It is a predefined keyword used for declaring static properties ormethods. A property defined as static can be accessed through scoperesolution operator. It cannot be accessed through object instance. Astatic method must be executed through scope resolution operator(::).A static method should not use $this keyword inside its code.Final : It is a predefined keyword used for specifying a class as finalor a method as final.
158Final class : A class specified as final cannot be extended to otherclass.Final method: A method specified as final cannot be overridden inextended class.Abstraction : abstract is a predefined keyword which is used fordefining abstract class or method.Abstract class : A class with atleast one abstract method must bedeclared as abstract class. An abstract class cannot be instantiateddirectly. An abstract class must be extended where abstract methodsmust be implemented with the code. An abstract class can haveproperties and constants. An abstract class should not contain privatemethods.Abstract methods : An abstract method should not contain body. Anabstract method cannot be private. abstract method must be declaredin its extended class along with its code.Ex: -<?phpabstract class a{public $x=10;const X=12;function abs(){echo "abstract method<br>";}}class B extends A{function abs(){echo "abstract method of extende class<br>";}
159}?>Interface :An interface is a collection of bodyless method without any accessspecifier. An interface won't allows the usage of declaration ofproperties or normal methods. An interface cannot be instantiateddirectly whereas it can be implemented by a class. The class whichimplements the interface must redeclare its bodyless methods in theclass. Multiple interfaces can be implemented by a class.Implements : It is a predefined keyword which is used for loading aninterface to a class.
160
161AJAXAJAX stands for Asynchronous JavaScript And XML. It is a clientside JavaScript method which is used for communication with theserver machine without any page refresh.1. To achieve asynchronous communication between browser andserver2. Updation of certain portions of the current webpage withoutReloading the entire webpage.AJAX is introduced in 2000 by Microsoft,it became very popularFrom 2005 onwards.AJAX is a browser dependent client side coding which is used forgetting the dynamic content from the server for JavaScript event inthe WebPages.AJAX communication will takes place in few steps.1. Creating a cross browser compatible AJAX.2. Opening the request to the server page.3. Sending the request.4. Checking the status of the request.5. On compilation of request loading the responded contentat the target element.Object in Internet Explorer :new ActiveXObject('Microsoft.XMLHTTP');new ActiveXObject('MSXML.XMLHTTP');new ActiveXObject('MSXML2.XMLHTTP');new ActiveXObject('MSXML3.XMLHTTP');new ActiveXObject('MSXMLC.XMLHTTP');
162Other than IE :new XMLHttpRequest();Opening Request :if(window.ActiveXObject){document.write("IE");}else if(window.XMLHttpRequest){document.write("Other than IE");}else {document.write("No Ajax support");}Open :open(method,url,async,[user_name],[password]);Ex : ajax.open("Get","getuser.php?id=2",true);Sending the Request :Send :send(null|<parameters>)Ex:-send(ajax.send(null);Properties of AJAX :a) Ready State :0uninitialised(Ajax engine is created,connection is not established)1initialised(open method will be called,connection established)
1632sent(send method is called,request is sent to server)3loading(request is under process)4completed(response received,process by AJAX engine completed)b) On ready state Change :Predefined event which will be called whenever ready state propertyvalue is updated.Ex :ajax.onreadystatechange=function(){if(ajax.readystate==4){document.write("ready state"<br>");}else{document.write("Not ready state<br>");}}c) Status :Here we will have the status code of the AJAX.200-> successful5xx->server issue4xx->page issue3xx->redirection
164d) Response Text :The information send from the server as text content.ajax.responseTexte) ResponseXML :Used for accessing response XML.ajax.responseXMLFlow of AJAX based Application :1. User action is performed on any of the HTML components Likebutton, hyperlink, selectbox, textbox etc.2. Certain JavaScript event is raised because of the above User action3. Specific user defined JavaScript function is called to handle Theabove raised JavaScript event.4. In the above JavaScript function Logic is written to create Ajax engine Partial form data is gathered Callback (user-defined) function is set toonreadystatechange Property of AJAX engine. URL is prepared along with every string Connection is established (open method is called) Request is sent to server (send () is called)5. Request related response comes to AJAX engine as text or XMLdata.6. Once again callback function is called. Inside callback function Logic to take response received by AJAX engine usingJavaScript Logic is written to update certain portions of thecurrentwebpages without reloading the entire webpagewith the receiver response.
165
166JOOMLAJOOMLA is a content management system. It is a CMS tool. It isdeveloped on php using mysql as its backend.JOOMLA is a objectoriented based tool which was developed on the Top of MVCarchitecture. JOOMLA comes with various predefined templates,components, modules, languages And plug-ins.JOOMLA software is available in various versions. (JOOMLA1.0.x,JOOMLA1.5.x, JOOMLA1.6.x).JOOMLA software consists of two interfaces.1. User interface (front end)2. Admin interface (Backend)1. User Interface : Front end is the actual website Which is shown tothe actual users of the website.2. Admin interface : Backend is the interface Which is accessiblefor the backend users for Managing the website with various actions.User Management :It allows the management of the Users to the website. Various typesof users are observed.a)Front end users : Registeredb)Special users : Editor, Publisherc)Backend users : Manager, Adminstrator, Super administrator.Media Management :It is used for managing media files in the software.Section management :Section : It is a top level hierarchy for content Classification. Itallows the management of sections.Category management :
167A category is the child category for a section used for sub classifyingthe content.Article Management :It can be considered as a webpage In the site which can be classifiedto a category Or a section.Component : A component is a functional block in the Websitewhich can be considered as Database Interaction and can be loaded atthe main (center) Portion of the website.Module : It is a functional block which can occupy various pre-defined positions in the software like top,left,right ,user 1,user 2, …..user n, footer etc. A module can be controlled for its display in One ormore pages.Plug-in : A plug-in is a logical part which will Enhance the way inwhich we will display the Content of the website.Template management :A template is a predefined Interface which is used for switching theuser Interfaces on the fly.Language management :JOOMLA supports multilingual Sites where we can install languageextension for Adding support with additional language.www.joomla.orgLatest version is 1.7Installation of JOOMLA :1. Install joomla without sample data2. Add all the users for each role3. Create few categories4. Create few articles.5. Add the menu links for the articles category
1686. Download free JOOMLA templates and install switch between thetemplates.7. Try to change logo of the template8. Install the external modules and plug-ins9. Activate free loaded modules and plug-ins.Check theirfunctionality10. create a website with few links using JOOMLA
169
170JQUERYJQuery is a JavaScript framework which is used For writing less codeand doing more action . JQuery is developed on top of java platformand it is used for creating rich website interface . JQuery is a fast andconcise JavaScript library . That simplifies HTML documenttraversing , event Handling, animating and Ajax interaction forRapid web development . JQuery is designed to Change the way thatyou write JavaScript.www.jquery.comSyntax :$(selector).methodSpecial Effects :Hide ()Show ()JQueryJQuery documentsJQuery core selectorJQuery supports css page selectorTraversingCSSEffectsEventsAJAX : implements JQuery plug-insUse JQuery pop calendarWrite JQuery cursorsJQuery based tool tips
171JQuery based light boxJQuery based form validationsJQuery based news agrigation using AJAXTHE END
172 Javascrtipt_Interview_Quesions PHP_Interview_questions
173Javascrtipt_Interview_Quesions1) <script type="text/javascript">x=4+"4";document.write(x);</script>Output------?a) 44b) 8c) 4d) Error outputAns: a2) <script type="text/javascript" language="javascript">var qpt = "Vempower Solutions";var result = qpt.split(" ");document.write(result);</script>a) Vempowerb) V,e,m,p,o,w,e,r, S,o,l,u,t,I,o,n,sc) Vempower Solutionsd) VempoweSolutionsAns: c3) Is it possible to nest functions in JavaScript?a) Trueb) FalseAns: a
1744) <script>document.write(navigator.appCodeName);</script>a) get code name of the browser of a visitorb) set code name of the browser of a visitorc) None of the aboveAns: a5) Which of the following is true?a) If onKeyDown returns false, the key-press event is cancelled.b) If onKeyPress returns false, the key-down event is cancelled.c) If onKeyDown returns false, the key-up event is cancelled.d) If onKeyPress returns false, the key-up event is canceled.Ans: a6) Scripting language area) High Level Programming languageb) Assembly Level programming languagec) Machine level programming languageAns: a7) <script language="javascript">function x(){var s= "Good 100%";var pattern = /D/g;var output= s.match(pattern);document.write(output);}</script>
175a) Good %b) 1,0,0c) G,o,o,d,%d) ErrorAns: c8) <script language="javascript">var qpt="Sample String ";alert(qpt.charAt(qpt.length-1));</script>a) pb) ec) gd) ErrorAns: c9) Are java and javascript the same?a) NOb) YESAns: a10) Syntax for creating a RegExp object:(a). var txt=new RegExp(pattern,attributes);(b). var txt=/pattern/attributes;Which of the above mentioned syntax will correct?a) (a) onlyb) (b) onlyc) Both (a) and (b)d) None of the above
176Ans: c11) <script language="javascript">function x(z,t){alert(x.length);}</script>output:?a) Errorb) 2c) 1d) 3Ans: b12) What is mean by "this" keyword in javascript?a) It refers current objectb) It referes previous objectc) It is variable which contains valued) None of the aboveAns: a13) In JavaScript, Window.prompt() method return true or false value?a) Falseb) Truec) None of aboveAns: a14) Math. round(-20.51)=?a) 20
177b) -21c) 19d) NoneAns: b15) <script language="javascript">function x(){var s = "Quality 100%!{[!!";var pattern = /w/g;var output = s.match(pattern);document.write(output);}</script>a) %,!,{,[,!,!b) Q,u,a,l,i,t,y,1,0,0c) Quality 100d) ErrorAns: b16) <script type="text/javascript" language="javascript">var qpt= new Array();qpt[0] = "WebDevelopment";qpt[1]="ApplicationDevelopment"qpt[2]="Testing"qpt[3] = "Vempower Solutions";document.write(qpt[0,1,2,3]);</script>a) Errorb) Vempower Solutionc) WebDevelopmentd) WebDevelopmnet,ApplicationDevelopment,Testing,VempowerSolutions
178Ans: b17) parseFloat(9+10)=?a) 19b) 910c) NoneAns: c18) <script language="javascript">function x(){document.write(2+5+"8");}</script>a) 258b) Errorc) 7d) 78Ans: d19) In Javascript, Which of the following method is used to evaluatethe regular expression?a) eval(2*(3+5))b) evaluate(2*(3+5))c) evalu(2*(3+5))d) None of the aboveAns: a20) <script language="javascript">function x(){var s= "quality 100%";
179var pattern = /d/g;var output= s.match(pattern);document.write(output);}</script>a) 100b) 1,0,0c) q,u,a,l,i,t,y,%d) ErrorAns: b21) <script type="text/javascript" language="javascript">qpt=((45%2)==0)? "hello" : "bye";document.write(qpt);</script>a) hellob) byec) Error in string handlingd) None of the aboveAns: b22) How do you create a new object in JavaScript?a) var obj = {};b) var obj = Object();c) var obj=new {};d) None of the aboveAns: a23) In Javascript, What does isNaN function do ?a) Return true if the argument is not a number.b) Return false if the argument is not a number.
180c) Return true if the argument is a number.d) None of the aboveAns: a24) Which of the following properties hold the values of the pixels ofthe length of the width and height of the viewer's screen resolution?a) screen.width and screen.heightb) Resolution.width and Resolution.heightc) screen.pixels.width and screen.pixels.heightd) ViewerScreen.width and ViewerScreen.heightAns: a25)How to assign a function to a variable with the JavaScriptFunction contructor ?a) var f=Function("x","y","return x+y");b) var f=Function(x,y){ return x+y;}c) var f= new Function("x", "y", "return x + y");Ans: b26) In JavaScript, Window.alert() is used to allow user to entersomethinga) Trueb) Falsec) None of aboveAns: b27) Is Javascript has any date data type?a) Yesb) NoAns: b
18128) ?_name is it valid javascript identifier?a) Yesb) NoAns: a29) <script type="text/javascript" language="javascript">var qpt="V-Empower Solutions ";var result =qpt.lastIndexOf("s");document.write(result);</script>a) -1b) 18c) 17d) 19Ans: 1830) <script language="javascript">function sum(x){function add(y){return x+y;}return add;}function callme() { result=sum(5)(5); alert(result); }</script>If you call the function callme(), what will happen ?a) 10b) Error in calling Functionc) 5
182d) None of the aboveAns: a31) <script type="text/javascript">document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");</script>Can you write HTML tag inside the javascript ?a) Nob) Yesc) ImpossibleAns: b32) How to speicfy the color of the hypertext links with JavaScript ?a) document.linkColor="#00FF00";b) document.LColor="#00FF00";c) document.LinkC="#00FF00";d) document.hyperTextLink="#00FF00":Ans: a33) ------------- converts a string to floating point numbers.a) evalb) ParseIntc) ParseFloatd) NoneAns: c34) In Javascript, Which of the following method is used to find outthe character at a position in a string?a) charAt()
183b) CharacterAt()c) CharPos()d) characAt()Ans: a35) <script type="text/javascript" language="javascript">var qpt = "V-Empower Solutions";var result =qpt.substring(7,8);document.write(result);</script>36) What are the following looping structures are available injavascripts?a) for,forecachb) foreach,whileloopc) do-while loop,foreachd) for , while loopAns: d37) Which of these is not a method of the Math object?a) atan()b) atan2()c) eval()d) acos()Ans: c38) <script type="text/javascript">var s = "9123456 or 80000?";var pattern = /d{4}/;var output = s.match(pattern);document.write(output);</script>
184a) 9123b) 91234c) 80000d) None of the aboveAns: a39) In javascript, RegExp Object Method test() is used to search astring and returnsa) true or falseb) found valuec) indexd) None of the aboveAns: a40) What property would you use to redirect a visitor to another page?a) document.URLb) window.location.hrefc) .document.location.hrefd) link.hrefAns: c41) -------------- method is used to remove focus from the specifiedobject.a) blur()b) focus()c) NoneAns: a42)Javascript is a ________ typed language.a) tightly
185b) looselyAns: b43)Choose the built-in object:a) Passwordb) Mathc) Linkd) HiddenAns: b44)Choose the object(s) associated with the onFocus event handler:a) Passwordb) Hiddenc) Bothd) NeitherAns: a45)Choose the object(s) associated with the onKeyPress eventhandler:a) Documentb) Layerc) Bothd) NeitherAns: a46)Choose the best pattern for the string: 840-21-3688a) /d+-d{2,}-?d*/b) /w+-w+-w+/c) /d+d+d+/d) /d+-d?-d+/
186Ans: a47) Which would JavaScript assign to an uninitialized variable?a) NaNb) nullc) undefinedd) falseAns: c48)Which is not a built-in function?a) parseInt()b) exec()c) eval()d) parseFloat()Ans: b49)Seek the truth about setTimeOut():a) The statement(s) it executes run(s) only once.b) It pauses the script in which it is called.c) clearTimeOut() won't stop its execution.d) The delay is measured in hundredths of a second.Ans: a50)How do you call a function named "myFunction"?a) call function myFunctionb) myFunction()c) call myFunction()Ans: c51) What is the correct JavaScript syntax for opening a new windowcalled "window2" ?a)new("http://www.w3schools.com","window2")
187b)new.window("http://www.w3schools.com","window2")c)window.open("http://www.w3schools.com","window2")d)open.new("http://www.w3schools.com","window2")Ans: c52)How do you find the client's browser name?a)client.navNameb)browser.namec)navigator.appNameAns: c53) Semicolons are optional at the end of a JavaScript statement.a)Trueb)FalseAns: a54)Which of the following are capabilities of functions in JavaScript?a) Return a valueb) Accept parameters and Return a valuec) Accept parametersd) None of the aboveAns: c55)Which popup box you use when want a value from user beforeopen a page?a) alert("Write some text here")b) confirm("Write some text here")c) prompt("Write here some text")d) None of the aboveAns: c56)What is the correct way to write a JavaScript array?a) var txt = new Array("tim","kim","jim")b) var txt = new Array="tim","kim","jim"c) var txt = new Array:1=("tim")2=("kim")3=("jim")d) var txt = new Array(1:"tim",2:"kim",3:"jim")Ans: a57) How to submit form data with javascript?
188a) document.formname.submit();b) submit()c) document.submit()d)None of the aboveAns: a58) When a user views a page containing a JavaScript program,which machine actually executes the script?a) The User's machine running a Web browserb) The Web serverc) A central machine deep within Netscape's corporate officesd) None of the aboveAns: a59) Which of the following is not a valid JavaScript variable name?a) 2namesb) _first_and_last_namesc) FirstAndLastd) None of the aboveAns:a60) To set up the window to capture all Click events, we use which ofthe following statement?a) window.captureEvents(Event.CLICK);b) window.handleEvents (Event.CLICK);c) window.routeEvents(Event.CLICK );d) window.raiseEvents(Event.CLICK ); Ans: aPHP_Interview_questionsQuestion: 1 Who is the father of PHP?
189Answer: Rasmus Lerdorf is known as the father of PHP.Question: 2 What is the difference between $name and $$name?Answer: $name is variable where as $$name is reference variablelike $name=sonia and $$name=singh so $sonia value is singh.Question: 3 How can we submit a form without a submit button?Answer: 3 Java script submit () function is used for submit formwithout submit buttonon click call document.formname.submit()Question : 4 In how many ways we can retrieve the data in theresult set ofMySQL using PHP?Answer : 4 We can do it by 4 Ways1. mysql_fetch_row.2. mysql_fetch_array3. mysql_fetch_object4. mysql_fetch_assocQuestion : 5 What is the difference between mysql_fetch_objectandmysql_fetch_array?Answer : 5 mysql_fetch_object() is similar tomysql_fetch_array(),with one difference -an object is returned, instead of an array. Indirectly, that means thatyou can only access the data by the field names, and not by theiroffsets (numbers are illegal property names).Question : 6 What are the differences between get and postmethods.Answer : 6 There are some defference between GET and POSTmethod1. GET Method have some limit like only 2Kb data able to send forrequestBut in POST method unlimited data can we send
1902. when we use GET method requested data show in url butNot in POST method so POST method is good for send sensetiverequestQuestion : 7 How can we extract string "pcds.co.in " from astring "http://info@pcds.co.in using regular expression of PHP?Answer : 7preg_match("/^http://.+@(.+)$/","http://info@pcds.co.in",$matches);echo $matches[1];Question : 8 How can we create a database using PHP andMySQL?Answer : 8 We can create MySQL database with the use ofmysql_create_db("Database Name") .Question : 9 What are the differences between require andinclude?Answer : 9 Both include and require used to include a file but whenincluded file not found Include send Warning where as Require sendFatal Error .Question : 10 Can we use include ("xyz.PHP") two times in aPHP page "index.PHP"?Answer : 10 Yes we can use include("xyz.php") more than one timein any page. but it create a prob when xyz.php file contain somefuntions declaration then error will come for already declared functionin this file else not a prob like if you want to show same content twotime in page then must incude it two time not a prob.Question : 11 What are the different tables(Engine) present inMySQL, which one is default?Answer : 11 Following tables (Storage Engine) we can create.1. MyISAM(The default storage engine IN MYSQL Each MyISAMtable is stored on disk in three files. The files have names that beginwith the table name and have an extension to indicate the file type. An.frm file stores the table format. The data file has an .MYD (MYData)
191extension. The index file has an .MYI (MYIndex) extension. )2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storageengine for MySQL that has commit, rollback, and crash-recoverycapabilities to protect user data.)3. Merge4. Heap (MEMORY)(The MEMORY storage engine creates tableswith contents that are stored in memory. Formerly, these were knownas HEAP tables. MEMORY is the preferred term, although HEAPremains supported for backward compatibility. )5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL withthe Berkeley DB transactional storage engine. This storage enginetypically is called BDB for short. BDB tables may have a greaterchance of surviving crashes and are also capable of COMMIT andROLLBACK operations on transactions)6. EXAMPLE7. FEDERATED (It is a storage engine that accesses data in tables ofremote databases rather than in local tables. )8. ARCHIVE (The ARCHIVE storage engine is used for storinglarge amounts of data without indexes in a very small footprint. )9. CSV (The CSV storage engine stores data in text files usingcomma-separated values format.)10. BLACKHOLE (The BLACKHOLE storage engine acts as a"black hole" that accepts data but throws it away and does not store it.Retrievals always return an empty result).Question : 12 What is use of header() function in php ?Answer : 12 The header() function sends a raw HTTP header to aclient.We can use herder() function for redirection of pages. It isimportant to notice that header() must be called before any actualoutput is seen.Question: 13 How can I execute a PHP script using commandline?Answer : 13 Just run the PHP CLI (Command Line Interface)program andprovide the PHP script file name as the command line argument.
192Question : 14 Suppose your Zend engine supports the mode <? ?>Then how can u configure your PHP Zend engine to support<?PHP ?> mode ?Answer : 14 In php.ini file: set short_open_tag=on to make PHPsupport .Question : 15 Shopping cart online validation i.e. how can weconfigure Paypal, etc.?Answer : 15 Nothing more we have to do only redirect to the payPalurl aftersubmit all information needed by paypal like amount,adresss etc.Question : 16 What is meant by nl2br()?Answer : 16 Inserts HTML line breaks (<BR />) before all newlinesin a string.Question : 17 What is htaccess? Why do we use this and Where?Answer : 17 .htaccess files are configuration files of Apache Serverwhich providea way to make configuration changes on a per-directory basis. A file,containing one or more configuration directives, is placed in aparticulardocument directory, and the directives apply to that directory, and allsubdirectories thereof.Question : 18 How we get IP address of client, previous referencepage etc?Answer : 18 By using$_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER']etc.Question : 19 What are the reasons for selecting lamp (Linux,apache, MySQL, PHP) instead of combination of other softwareprograms, servers and perating systems?Answer : 19 All of those are open source resource. Security of Linuxis very
193very more than windows. Apache is a better server that IIS both infunctionality and security. MySQL is world most popular open sourcedatabase. PHP is more faster that asp or any other scripting language.Question : 20 How can we encrypt and decrypt a data present in aMySQL table using MySQL?Answer : 20 AES_ENCRYPT () and AES_DECRYPT ().Question : 21 How can we encrypt the username and passwordusing PHP?Answer : 21 The functions in this section perform encryption anddecryption, andcompression and uncompression:encryption DecryptionAES_ENCRYT() AES_DECRYPT()ENCODE() DECODE()DES_ENCRYPT() DES_DECRYPT()ENCRYPT() Not availableMD5() Not availableOLD_PASSWORD() Not availablePASSWORD() Not availableSHA() or SHA1() Not availableNot available UNCOMPRESSED_LENGTH()Question : 22 What are the features and advantages of object-orientedprogramming?
194Answer : 22 One of the main advantages of OO programming is itsease ofmodification; objects can easily be modified and added to a systemthereby reducing maintenance costs. OO programming is also consideredto bebetter at modeling the real world than is procedural programming. Itallows for more complicated and flexible interactions. OO systemsarealso easier for non-technical personnel to understand and easier forthem to participate in the maintenance and enhancement of a systembecause it appeals to natural human cognition patterns.For some systems, an OO approach can speed development time sincemanyobjects are standard across systems and can be reused. Componentsthatmanage dates, shipping, shopping carts, etc. can be purchased andeasilymodified for a specific system.Question : 23 What are the differences between procedure-oriented languages and object-oriented language?Answer : 23 There are lot of difference between procedure languageand object oriented like below1>Procedure language easy for new developer but complex tounderstand whole software as compare to object oriented model2>In Procedure language it is difficult to use design pattern mvc ,Singleton pattern etc but in OOP you we able to develop designpattern3>IN OOP language we able to ree use code like Inheritance,polymorphism etc but this type of thing not available in procedurelanguage on that our Fonda use COPY and PASTE .Question : 24 What is the use of friend function?Answer : 24 Sometimes a function is best shared among a number ofdifferentclasses. Such functions can be declared either as member functions of
195one class or as global functions. In either case they can be set to befriends of other classes, by using a friend specifier in the class thatis admitting them. Such functions can use all attributes of the classwhich names them as a friend, as if they were themselves members ofthatclass.A friend declaration is essentially a prototype for a member function,but instead of requiring an implementation with the name of that classattached by the double colon syntax, a global function or memberfunction of another class provides the match.Question : 25 What are the differences between public, private,protected,static, transient, final and volatile?Answer : 25 Public: Public declared items can be accessedeverywhere.Protected: Protected limits access to inherited and parentclasses (and to the class that defines the item).Private: Private limits visibility only to the class that definesthe item.Static: A static variable exists only in a local function scope,but it does not lose its value when program execution leaves thisscope.Final: Final keyword prevents child classes from overriding amethod by prefixing the definition with final. If the class itself isbeing defined final then it cannot be extended.transient: A transient variable is a variable that may notbe serialized.volatile: a variable that might be concurrently modified by multiplethreads should be declared volatile. Variables declared to be volatilewill not be optimized by the compiler because their value can changeatany time.Question : 26 What are the different types of errors in PHP?Answer : 26 Three are three types of errors:1. Notices: These aretrivial,
196non-critical errors that PHP encounters while executing a script –forexample, accessing a variable that has not yet been defined. Bydefault,such errors are not displayed to the user at all – although, as youwillsee, you can change this default behavior.2. Warnings: These aremore serious errors – for example, attemptingto include() a file which does not exist. By default, these errors aredisplayed to the user, but they do not result in script termination.3.Fatal errors: These are critical errors – for example,instantiating an object of a non-existent class, or calling anon-existent function. These errors cause the immediate terminationofthe script, and PHP's default behavior is to display them to the userwhen they take place.Question : 27 What is the functionality of the function strstr andstristr? Answer : 27 strstr Returns part of string from the firstoccurrence of needle(sub string that we finding out ) to the end ofstring.$email= 'sonialouder@gmail.com';$domain = strstr($email, '@');echo $domain; // prints @gmail.comhere @ is the needlestristr is case-insensitive means able not able to differentiate betweena and A.Question : 28 What are the differences between PHP 3 and PHP 4and PHP 5?Answer : 28 There are lot of difference among these three version ofphp1.Php3 is oldest version after that php4 came and current version isphp5 (php5.3) where php6 have to come2.Difference mean oldest version have less functionality as compareto new one like php5 have all OOPs concept now where as php3 waspure procedural language constructive like CIn PHP5 1. Implementation of exceptions and exception handling
1972. Type hinting which allows you to force the type of a specificargument3. Overloading of methods through the __call function4. Full constructors and destructors etc through a __constructor and__destructor function5. __autoload function for dynamically including certain include filesdepending on the class you are trying to create.6 Finality : can now use the final keyword to indicate that a methodcannot be overridden by a child. You can also declare an entire classas final which prevents it from having any children at all.7 Interfaces & Abstract Classes8 Passed by Reference :9 An __clone method if you really want to duplicate an object.Question : 29 How can we convert asp pages to PHP pages?Answer : 29 there are lots of tools available for asp to PHPconversion. you cansearch Google for that. the best one is availableathttp://asp2php.naken.cc./.Question : 30 What is the functionality of the functionhtmlentities? Answer : 30 Convert all applicable characters toHTML entitiesThis function is identical to htmlspecialchars() in all ways, exceptwith htmlentities(), all characters which have HTML character entityequivalents are translated into these entities.Question : 31 How can we get second of the current time usingdate function?Answer : 31 $second = date("s");Question : 32 How can we convert the time zones using PHP?Answer : 32 By using date_default_timezone_get anddate_default_timezone_set function on PHP 5.1.0<?php// Discover what 8am in Tokyo relates to on the East Coast of the US// Set the default timezone to Tokyo time:
198date_default_timezone_set('Asia/Tokyo');// Now generate the timestamp for that particular timezone, on Jan 1st,2000$stamp = mktime(8, 0, 0, 1, 1, 2000);// Now set the timezone back to US/Easterndate_default_timezone_set('US/Eastern');// Output the date in a standard format (RFC1123), this will print:// Fri, 31 Dec 1999 18:00:00 ESTecho '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>Question : 33 What is meant by urlencode and urldocode?Answer : 33 URLencode returns a string in which all non-alphanumeric charactersexcept -_. have been replaced with a percent (%) sign followed bytwo hex digits and spaces encoded as plus (+) signs. It is encoded thesame way that the posted data from a WWW form is encoded, that isthe same way as inapplication/x-www-form-urlencoded media type.urldecode decodes any %##encoding in the given string.Question : 34 What is the difference between the functions unlinkand unset?Answer : 34 unlink() deletes the given file from the file system.unset() makes a variable undefined.Question : 35 How can we register the variables into a session?Answer : 35 $_SESSION['name'] = "sonia";Question : 36 How can we get the properties (size, type, width,height) of an image using PHP image functions?Answer : 36 To know the Image type use exif_imagetype () functionTo know the Image size use getimagesize () functionTo know the image width use imagesx () functionTo know the image height use imagesy() function.
199Question : 37 How can we get the browser properties using PHP?Answer : 37 By using $_SERVER['HTTP_USER_AGENT']variable.Question : 38 What is the maximum size of a file that can beuploaded using PHP and how can we change this?Answer : 38 By default the maximum size is 2MB. and we canchange the followingsetup at php.ini upload_max_filesize = 2M.Question : 39 How can we increase the execution time of a PHPscript? Answer : 39 by changing the following setup at php.inimax_execution_time = 30; Maximum execution time of each script, in seconds.Question : 40 How can we take a backup of a MySQL table andhow can we restore it. ?Answer : 40 To backup: BACKUP TABLE tbl_name[,tbl_name…]TO'/path/to/backup/directory'. RESTORE TABLEtbl_name[,tbl_name…] FROM'/path/to/backup/directory'mysqldump: Dumping Table Structure andDataUtility to dump a database or a collection of database for backuporfor transferring the data to another SQL server (not necessarily aMySQLserver). The dump will contain SQL statements to create the tableand/orpopulate the table.Question : 41 How can we optimize or increase the speed of aMySQL selectquery?Answer : First of all instead of using select * from table1, use selectcolumn1, column2, column3.. from table1
200 Look for the opportunity to introduce index in the table you arequerying. Use limit keyword if you are looking for any specific number ofrows from the result set.Question : 42 How many ways can we get the value of currentsession id?Answer : 42 session_id() returns the session id for the currentsession.Question : 43 How can we destroy the session, how can we unsetthe variable of a session?Answer : 43 session_unregister to Unregister a global variable fromthe currentsession session_unset to Free all session variables.Question : 44 How can we set and destroy the cookie n php?Answer : 44 By using setcookie(name, value, expire, path, domain);function we can set the cookie in php ;Set the cookies in past for destroy. likesetcookie("user", "sonia", time()+3600); for set the cookiesetcookie("user", "", time()-3600); for destroy or delete the cookies;Question : 45 How many ways we can pass the variable throughthe navigation between the pages?Answer : 45. GET/QueryString POSTQuestion : 46 What is the difference between ereg_replace() anderegi_replace()?Answer : 46 eregi_replace() function is identical to ereg_replace()except thatthis ignores case distinction when matching alphabeticcharacters.eregi_replace() function is identical to ereg_replace()
201except that this ignores case distinction when matching alphabeticcharacters.Question : 47 What are the different functions in sorting anarray?Answer : 47 Sort(), arsort(),asort(), ksort(),natsort(), natcasesort(),rsort(), usort(),array_multisort(), and uksort().Question : 48 How can we know the count/number of elements ofan array?Answer : 48 2 waysa) sizeof($urarray) This function is an alias of count()b) count($urarray)Question : 49 what is session_set_save_handler in PHP?Answer : 49 session_set_save_handler() sets the user-level sessionstorage functions which are used for storing and retrieving dataassociated with a session. This is most useful when a storage methodother than those supplied by PHP sessions is preferred. i.e. Storing thesession data in a local database.Question : 50 How can I know that a variable is a number or notusing aJavaScript?Answer : 50 bool is_numeric ( mixed var) Returns TRUE if var is anumber or a numeric string, FALSE otherwise.or use isNaN(mixedvar)The isNaN() function is used to check if a value is not a number.Question : 51 List out some tools through which we can draw E-Rdiagrams for mysql.Answer : 51 Case Studio Smart Draw.Question : 52 How can I retrieve values from one database serverand store them in other database server using PHP?Answer : 52 we can always fetch from one database and rewrite toanother. here
202is a nice solution of it.$db1 = mysql_connect("host","user","pwd")mysql_select_db("db1", $db1);$res1 = mysql_query("query",$db1);$db2 =mysql_connect("host","user","pwd")mysql_select_db("db2", $db2);$res2 = mysql_query("query",$db2);At this point you can only fetchrecords from you previous ResultSet,i.e $res1 But you cannot execute new query in $db1, even if yousupply the link as because the link was overwritten by the new db.soat this point the following script will fail.$res3 = mysql_query("query",$db1); //this will failSo how to solvethat?take a look below.$db1 = mysql_connect("host","user","pwd")mysql_select_db("db1", $db1);$res1 = mysql_query("query",$db1);$db2 = mysql_connect("host","user","pwd", true)mysql_select_db("db2", $db2);$res2 = mysql_query("query",$db2);So mysql_connect has another optional boolean parameter whichindicates whether a link will be created or not. as we connect to the$db2 with this optional parameter set to 'true', so both link willremain live.now the following query will execute successfully.$res3 = mysql_query("query",$db1);Question : 53 List out the predefined classes in PHP?Answer : 53 Directory stdClass __PHP_Incomplete_Class exceptionphp_user_filter.Question : 54 How can I make a script that can be bi-language(supportsEnglish, German)?
203Answer : 54 You can maintain two separate language file for each ofthelanguage. all the labels are putted in both language files as variablesand assign those variables in the PHP source. on runtime choose therequired language option.Question : 55 What are the difference between abstract class andinterface?Answer : 55 Abstract class: abstract classes are the class where oneor moremethods are abstract but not necessarily all method has to be abstract.Abstract methods are the methods, which are declare in its class butnotdefine. The definition of those methods must be in its extendingclass.Interface: Interfaces are one type of class where all the methodsareabstract. That means all the methods only declared but not defined.Allthe methods must be define by its implemented class.Question : 56 How can we send mail using JavaScript?Answer : 56 JavaScript does not have any networking capabilities asit isdesigned to work on client site. As a result we can not send mailsusingJavaScript. But we can call the client side mail protocol mailtovia JavaScript to prompt for an email to send. this requires the clientto approve it.Question : 57 How can we repair a MySQL table?Answer : 57 The syntex for repairing a MySQL table isREPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]This command will repair the table specified if the quick is given theMySQL will do a repair of only the index tree if the extended is givenit will create index row by row.Question : 58 What are the advantages of stored procedures,triggers, indexes?
204Answer : 58 A stored procedure is a set of SQL commands that canbe compiled and stored in the server. Once this has been done, clientsdon't need tokeep re-issuing the entire query but can refer to the stored procedure.This provides better overall performance because the query has to beparsed only once, and less information needs to be sent between theserver and the client. You can also raise the conceptual level byhavinglibraries of functions in the server. However, stored procedures ofcourse do increase the load on the database server system, as more ofthe work is done on the server side and less on the client (application)side.Triggers will also be implemented. A trigger is effectively a typeofstored procedure, one that is invoked when a particular event occurs.For example, you can install a stored procedure that is triggered eachtime a record is deleted from a transaction table and that storedprocedure automatically deletes the corresponding customer from acustomer table when all his transactions are deleted.Indexes are usedto find rows with specific column values quickly.Without an index, MySQL must begin with the first row and then readthrough the entire table to find the relevant rows. The larger thetable, the more this costs. If the table has an index for the columns inquestion, MySQL can quickly determine the position to seek to in themiddle of the data file without having to look at all the data. If atable has 1,000 rows, this is at least 100 times faster than readingsequentially. If you need to access most of the rows, it is faster toread sequentially, because this minimizes disk seeks.Question : 59 What is the maximum length of a table name,database name, and fieldname in MySQL?Answer : 59 The following table describes the maximum length foreach type ofidentifier.IdentifierMaximum Length(bytes)
205Database 64Table 64Column 64Index 64Alias 255There are some restrictions on the characters that may appear inidentifiers:Question : 60 How many values can the SET function of MySQLtake?Answer : 60 MySQL set can take zero or more values but at themaximum it cantake 64 values.Question : 61 What are the other commands to know thestructure of table using MySQL commands except explaincommand?Answer : 61 describe Table-Name;Question : 62 How many tables will create when we create table,what are they?Answer : 62 The '.frm' file stores the table definition.The data file has a '.MYD' (MYData) extension.The index file has a '.MYI' (MYIndex) extension.Question : 63 What is the purpose of the following files havingextensions 1) .frm 2) .myd 3) .myi? What do these files contain?Answer : 63 In MySql, the default table type is MyISAM.Each MyISAM table is stored on disk in three files. The files havenamesthat begin with the table name and have an extension to indicate thefile type.The '.frm' file stores the table definition.
206The data file has a '.MYD' (MYData) extension.The index file has a '.MYI' (MYIndex) extension.Question : 64 What is maximum size of a database in MySQL?Answer : 64 If the operating system or filesystem places a limit onthe numberof files in a directory, MySQL is bound by that constraint.Theefficiency of the operating system in handling large numbers of filesin a directory can place a practical limit on the number of tables in adatabase. If the time required to open a file in the directory increasessignificantly as the number of files increases, databaseperformance can be adversely affected. The amount of available diskspace limits the number of tables.MySQL 3.22 had a 4GB (4gigabyte) limit on table size. With the MyISAM storage engine inMySQL 3.23, the maximum table size was increased to65536 terabytes (2567 – 1 bytes). With this larger allowed tablesize,the maximum effective table size for MySQL databases is usuallydetermined by operating system constraints on file sizes, not byMySQL internal limits.The InnoDB storage engine maintains InnoDBtables within a tablespace that can be created from several files. Thisallows a table to exceed the maximum individual file size. Thetablespace can include raw disk partitions, which allows extremelylarge tables. The maximum tablespace size is 64TB. The followingtable lists some examples of operating system file-sizelimits. This isonly a rough guide and is not intended to be definitive.For the mostup-to-date information, be sure to check the documentationspecific to your operating system.Operating System File-size.LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB) Linux 2.4+ (using ext3filesystem) 4TBSolaris 9/10 16TBNetWare w/NSS filesystem 8TBWin32 w/ FAT/FAT32 2GB/4GBWin32 w/ NTFS 2TB (possibly larger)MacOS X w/ HFS+ 2TB.Question : 65 Give the syntax of Grant and Revoke commands?Answer : 65 The generic syntax for grant is as followingGRANT [rights] on [database/s] TO [username@hostname]
207IDENTIFIED BY [password] now rights can bea) All privilegesb) combination of create, drop, select, insert, update and delete etc.Wecan grant rights on all databse by using *.* or some specificdatabase by database.* or a specific table by database.table_nameusername@hotsname can be either username@localhost,username@hostnameand username@%where hostname is any valid hostname and % represents any name,the *.*any conditionpassword is simply the password of userThe generic syntax for revokeis as followingREVOKE [rights] on [database/s] FROM [username@hostname] nowrights can be as explained abovea) All privilegesb) combination of create, drop, select, insert, update and delete etc.username@hotsname can be either username@localhost,username@hostnameand username@%where hostname is any valid hostname and % represents any name,the *.*any conditionQuestion : 66 Explain Normalization concept?Answer : 66 The normalization process involves getting our data toconform tothree progressive normal forms, and a higher level of normalizationcannot be achieved until the previous levels have been achieved (thereare actually five normal forms, but the last two are mainly academicandwill not be discussed).First Normal FormThe First Normal Form (or1NF) involves removal of redundant datafrom horizontal rows. We want to ensure that there is no duplicationofdata in a given row, and that every column stores the least amount ofinformation possible (making the field atomic).Second Normal
208FormWhere the First Normal Form deals with redundancy of dataacross ahorizontal row, Second Normal Form (or 2NF) deals with redundancyofdata in vertical columns. As stated earlier, the normal forms areprogressive, so to achieve Second Normal Form, your tables mustalreadybe in First Normal Form.Third Normal FormI have a confession to make; I do not often use Third Normal Form. InThird Normal Form we are looking for data in our tables that is notfully dependant on the primary key, but dependant on another value inthe tableQuestion : 67 How can we find the number of rows in a tableusing MySQL? Answer : 67 Use this for mysql SELECTCOUNT(*) FROM table_name;Question : 68 How can we find the number of rows in a result setusing PHP?Answer : 68 $result = mysql_query($sql, $db_link);$num_rows = mysql_num_rows($result);echo "$num_rows rows found";Question : 69 How many ways we can we find the current dateusing MySQL?Answer : 69 SELECT CURDATE();CURRENT_DATE() = CURDATE()for time useSELECT CURTIME();CURRENT_TIME() = CURTIME()Question : 70 What are the advantages and disadvantages ofCascading Style Sheets?Answer : 70 External Style SheetsAdvantagesCan control styles formultiple documents at once. Classes can be created for use onmultiple HTML element types in many documents. Selector andgrouping methods can be used to apply styles under complex
209contextsDisadvantagesAn extra download is required to import styleinformation for each document The rendering of the document maybe delayed until the external style sheet is loaded Becomes slightlyunwieldy for small quantities ofstyle definitions Embedded StyleSheets Advantages Classes can be created for use on multiple tagtypes in the document. Selector and grouping methods can be used toapply styles under complex contexts. No additional downloadsnecessary to receive style informationDisadvantagesThis method can not control styles for multiple documents at onceInline StylesAdvantagesUseful for small quantities of style definitions. Can override otherstyle specification methods at the local level so only exceptions needto be listed in conjunction with other style methods.DisadvantagesDoes not distance style information from content (a main goal ofSGML/HTML). Can not control styles for multiple documents atonce. Author can not create or control classes of elements to controlmultiple element types within the document. Selector groupingmethods can not be used to create complex element addressingscenariosQuestion : 71 What type of inheritance that PHP supports?Answer : 71 In PHP an extended class is always dependent on asingle base class,that is, multiple inheritance is not supported. Classes are extendedsing the keyword 'extends'.Question : 72 What is the difference between Primary Key andUnique key?
210Answer : 72 Primary Key: A column in a table whose valuesuniquely identify therows in the table. A primary key value cannot be NULL.Unique Key: Unique Keys are used to uniquely identify each row inthe table. There can be one and only one row for each unique keyvalue. So NULL can be a unique key.There can be only one primarykey for a table but there can be more than one unique for a table.Question : 73 what is garbage collection? default time ? refreshtime?Answer : 73 Garbage Collection is an automated part of PHP , If theGarbage Collection process runs, it then analyzes any files in the /tmpfor any session files that have not been accessed in a certain amountof time and physically deletes them. Garbage Collection process onlyruns in the default session save directory, which is /tmp. If you opt tosave your sessions in a different directory, the Garbage Collectionprocess will ignore it. the Garbage Collection process does notdifferentiate between which sessions belong to whom when run. Thisis especially important note on shared web servers. If the process isrun, it deletes ALL files that have not been accessed in the directory.There are 3 PHP.ini variables, which deal with the garbage collector:PHP ini value name default session.gc_maxlifetime 1440 seconds or24 minutes session.gc_probability 1 session.gc_divisor 100.Question : 74 What are the advantages/disadvantages of MySQLand PHP? Answer : 74 Both of them are open source software (sofree of cost), supportcross platform. php is faster then ASP and JSP.Question : 75 What is the difference between GROUP BY andORDER BY in Sql? Answer : 75 ORDER BY[col1],[col2],…,[coln]; Tels DBMS according to what columns itshould sort the result. If two rows will hawe the same value in col1it will try to sort them according to col2 and so on.GROUP BY[col1],[col2],…,[coln]; Tels DBMS to group results with same valueofcolumn col1. You can use COUNT(col1), SUM(col1), AVG(col1)
211with it, ifyou want to count all items in group, sum all values or view average.Question : 76 What is the difference between char and varchardata types? Answer : 76 Set char to occupy n bytes and it will take nbytes even if u r storing a value of n-m bytes Set varchar to occupy nbytes and it will take only the required space and will not use the nbyteseg. name char(15) will waste 10 bytes if we store 'romharshan', if eachchartakes a byteeg. name varchar(15) will just use 5 bytes if we store 'romharshan', ifeachchar takes a byte. rest 10 bytes will be free.Question : 77 What is the functionality of md5 function in PHP?Answer : 77 Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use toidentify users etc. If I add random no techniques to it the md5generated nowwill be totally different for the same string I am using.Question : 78 How can I load data from a text file into a table?Answer : 78 you can use LOAD DATA INFILE file_name; syntax toload data from a text file. but you have to make sure thata) data isdelimited b) columns and data matched correctly.Question : 79 How can we know the number of days between twogiven dates using MySQL?Answer : 79 SELECT DATEDIFF("2007-03-07","2005-01-01");Question : 80 How can we know the number of days between twogiven dates using PHP?Answer : 80 $date1 = date("Y-m-d");$date2 = "2006-08-15";$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);Question : 81 How we load all classes that placed in differentdirectory in one PHP File , means how to do auto load classes.
212Answer : 81by using spl_autoload_register('autoloader::funtion');Like belowclass autoloader{public static function moduleautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] ."/modules/{$class}.php";if (is_readable($path)) require $path;}public static function daoautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] ."/dataobjects/{$class}.php";if (is_readable($path)) require $path;}public static function includesautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] ."/includes/{$class}.php";if (is_readable($path)) require $path;}}spl_autoload_register('autoloader::includesautoloader');spl_autoload_register('autoloader::daoautoloader');spl_autoload_register('autoloader::moduleautoloader');Question : 82 How many types of Inheritances used in PHP andhow we achieve it.
213Answer : 82 As far PHP concern it only support single Inheritance inscripting.we can also use interface to achieve multiple inheritance.Question : 83 PHP how to know user has read the email?Answer : 83 Using Disposition-Notification-To: in mailheader wecan get read receipt.Add the possibility to define a read receipt whensending an email.It’s quite straightforward, just edit email.php, and add this at varsdefinitions:var $readReceipt = null;And then, at ‘createHeader’ function add:if (!empty($this->readReceipt)) {$this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine;}Question : 84 What are default session time and path?Answer : 84 default session time in PHP is 1440 seconds or 24minutesDefault session save path id temporary folder /tmp.Question : 85 how to track user logged out or not? when user isidle ? Answer : 85 By checking the session variable exist or notwhile loading th page. As the session will exist longer as till browsercloses. The default behaviour for sessions is to keep a session openindefinitely and only to expire a session when the browser is closed.This behaviour can be changed in the php.ini file by altering the linesession.cookie_lifetime = 0 to a value in seconds. If you wanted thesession to finish in 5 minutes you would set this tosession.cookie_lifetime = 300 and restart your httpd server.Question : 86 how to track no of user logged in ?Answer : 86 whenever a user logs in track the IP, userID etc..andstore it in a DB with a active flag while log out or sesion expire makeit inactive. At any time by counting the no: of active records we canget the no: of visitors.
214Question : 87 in PHP for pdf which library used?Answer : 87 The PDF functions in PHP can create PDF files usingthe PDFlib library With version 6, PDFlib offers an object-orientedAPI for PHP 5 in addition to the function-oriented API for PHP 4.There is also the » Panda module. FPDF is a PHP class whichallows to generate PDF files with pure PHP, that is to say withoutusing the PDFlib library. F from FPDF stands for Free: you may use itfor any kind of usage and modify it to suit your needs. FPDF requiresno extension (except zlib to activate compression and GD for GIFsupport) and works with PHP4 and PHP5.Question : 88 for image work which library?Answer : 88 we will need to compile PHP with the GD library ofimage functions for this to work. GD and PHP may also require otherlibraries, depending on which image formats you want to work with.Question : 89 what is design pattern? singleton pattern?Answer : 89 A design pattern is a general reusable solution to acommonly occurring problem in software design. The Singletondesign pattern allows many parts of a program to share a singleresource without having to work out the details of the sharingthemselves.Question : 90 what are magic methods?Answer : 90 Magic methods are the members functions that isavailable to all the instance of class Magic methods always starts with"__". Eg. __construct All magic methods needs to be declared aspublic To use magic method they should be defined within the classor program scope Various Magic Methods used in PHP 5 are:__construct() __destruct() __set() __get() __call() __toString()__sleep() __wakeup() __isset() __unset() __autoload() __clone().Question : 91 what is magic quotes?Answer : 91 Magic Quotes is a process that automatically escapesincoming data to the PHP script. It’s preferred to code with magicquotes off and to instead escape the data at runtime, as needed. This
215feature has been DEPRECATED as of PHP 5.3.0 and REMOVED asof PHP 6.0.0. Relying on this feature is highly discouraged.Question : 92 what is cross site scripting? SQL injection?Answer : 92 Cross-site scripting (XSS) is a type of computer securityvulnerability typically found in web applications which allow codeinjection by malicious web users into the web pages viewed by otherusers. Examples of such code include HTML code and client-sidescripts. SQL injection is a code injection technique that exploits asecurity vulnerability occurring in the database layer of anapplication. The vulnerability is present when user input is eitherincorrectly filtered for string literal escape characters embedded inSQL statements or user input is not strongly typed and therebyunexpectedly executed.Question : 93 what is URL rewriting?Answer : 93 Using URL rewriting we can convert dynamic URl tostatic URL Static URLs are known to be better than Dynamic URLsbecause of a number of reasons 1. Static URLs typically Rank betterin Search Engines. 2. Search Engines are known to index the contentof dynamic pages a lot slower compared to static pages. 3. StaticURLs are always more friendlier looking to the End Users. along withthis we can use URL rewriting in adding variables [cookies] to theURL to handle the sessions.Question : 94 what is the major php security hole? how to avoid?Answer : 94 1. Never include, require, or otherwise open a file with afilename based on user input, without thoroughly checking it first.2. Be careful with eval() Placing user-inputted values into the eval()function can be extremely dangerous. You essentially give themalicious user the ability to execute any command he or she wishes!3. Be careful when using register_globals = ON It was originallydesigned to make programming in PHP easier (and that it did), butmisuse of it often led to security holes4. Never run unescaped queries5. For protected areas, use sessions or validate the login every time.
2166. If you don’t want the file contents to be seen, give the file a .phpextension.Question : 95 whether PHP supports Microsoft SQL server ?Answer : 95 The SQL Server Driver for PHP v1.0 is designed toenable reliable, scalable integration with SQL Server for PHPapplications deployed on the Windows platform. The Driver for PHPis a PHP 5 extension that allows the reading and writing of SQLServer data from within PHP scripts. using MSSQL or ODBCmodules we can access Microsoft SQL server.Question : 96 what is MVC? why its been used?Answer : 96 Model-view-controller (MVC) is an architectural patternused in software engineering. Successful use of the pattern isolatesbusiness logic from user interface considerations, resulting in anapplication where it is easier to modify either the visual appearance ofthe application or the underlying business rules without affecting theother. In MVC, the model represents the information (the data) of theapplication; the view corresponds to elements of the user interfacesuch as text, checkbox items, and so forth; and the controller managesthe communication of data and the business rules used to manipulatethe data to and from the model. WHY ITS NEEDED IS 1 Modularseparation of function 2 Easier to maintain 3 View-Controllerseparation means:A Tweaking design (HTML) without altering code B Web designstaff can modify UI without understanding code.Question : 97 what is framework? how it works? what isadvantage? Answer : 97 In general, a framework is a real orconceptual structure intended to serve as a support or guide for thebuilding of something that expands the structure into somethinguseful. Advantages : Consistent Programming Model Direct Supportfor Security Simplified Development Efforts Easy ApplicationDeployment and Maintenance.Question : 98 what is CURL?Answer : 98 CURL means Client URL Librarycurl is a command line tool for transferring files with URL syntax,
217supporting FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET,DICT, LDAP, LDAPS and FILE. curl supports SSL certificates,HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload,proxies, cookies, user+password authentication (Basic, Digest,NTLM, Negotiate), file transfer resume, proxy tunneling and abusload of other useful tricks. CURL allows you to connect andcommunicate to many different types of servers with many differenttypes of protocols. libcurl currently supports the http, https, ftp,gopher, telnet, dict, file, and ldap protocols. libcurl also supportsHTTPS certificates, HTTP POST, HTTP PUT, FTP uploading. HTTPform based upload, proxies, cookies, and user+passwordauthentication.Question : 99 what is PDO ?Answer : 99The PDO ( PHP Data Objects ) extension defines a lightweight,consistent interface for accessing databases in PHP. if you are usingthe PDO API, you could switch the database server you used, fromsay PgSQL to MySQL, and only need to make minor changes to yourPHP code. While PDO has its advantages, such as a clean, simple,portable API but its main disadvantage is that it doesn't allow you touse all of the advanced features that are available in the latest versionsof MySQL server. For example, PDO does not allow you to useMySQL's support for Multiple Statements.Just need to use below code for connect mysql using PDOtry {$dbh = new PDO("mysql:host=$hostname;dbname=databasename",$username, $password);$sql = "SELECT * FROM employee";foreach ($dbh->query($sql) as $row){print $row['employee_name'] .' - '. $row['employee_age'] ;}}catch(PDOException $e){
218echo $e->getMessage();}Question : 100 What is PHP's mysqli Extension ?Answer : 100The mysqli extension, or as it is sometimes known, the MySQLimproved extension, was developed to take advantage of new featuresfound in MySQL systems versions 4.1.3 and newer. The mysqliextension is included with PHP versions 5 and later.The mysqli extension has a number of benefits, the key enhancementsover the mysql extension being:=>Object-oriented interface=>Support for Prepared Statements=>Support for Multiple Statements=>Support for Transactions=>Enhanced debugging capabilitiesB.Praveen Kumar(Trainer in PHP)Sathya Technology,Ameerpete-mailid:praveen.lamp@gmail.comStudent e-mailid:ankushsuryawanshi9@gmail.com

Recommended

PPTX
HTML Text formatting tags
PPTX
Html notes with Examples
 
PPTX
PDF
Basic html
PPT
Intro to html
PPT
Html Slide Part-1
PPSX
Introduction to Html5
PPTX
The Complete HTML
PPTX
Html, CSS & Web Designing
PDF
Girl Develop It Cincinnati: Intro to HTML/CSS Class 2
PPT
CSS Basics
PPT
Html basics
PPTX
Html
PPT
Cascading Style Sheets (CSS) help
PPTX
Complete Lecture on Css presentation
PDF
Frontend Crash Course: HTML and CSS
ODP
CSS Basics
PPTX
Cascading Style Sheet (CSS)
PDF
Introduction to HTML and CSS
PPTX
Basic html structure
ODP
HTML5
PPTX
Html and css
PDF
HTTP Request and Response Structure
PPTX
Web Page Designing Using HTML
PPTX
Meta tags
 
PPTX
Http
PPTX
Html audio video
PDF
Basic Html Notes
PPTX
Php Tutorial

More Related Content

PPTX
HTML Text formatting tags
PPTX
Html notes with Examples
 
PPTX
PDF
Basic html
PPT
Intro to html
PPT
Html Slide Part-1
PPSX
Introduction to Html5
PPTX
The Complete HTML
HTML Text formatting tags
Html notes with Examples
 
Basic html
Intro to html
Html Slide Part-1
Introduction to Html5
The Complete HTML

What's hot

PPTX
Html, CSS & Web Designing
PDF
Girl Develop It Cincinnati: Intro to HTML/CSS Class 2
PPT
CSS Basics
PPT
Html basics
PPTX
Html
PPT
Cascading Style Sheets (CSS) help
PPTX
Complete Lecture on Css presentation
PDF
Frontend Crash Course: HTML and CSS
ODP
CSS Basics
PPTX
Cascading Style Sheet (CSS)
PDF
Introduction to HTML and CSS
PPTX
Basic html structure
ODP
HTML5
PPTX
Html and css
PDF
HTTP Request and Response Structure
PPTX
Web Page Designing Using HTML
PPTX
Meta tags
 
PPTX
Http
PPTX
Html audio video
Html, CSS & Web Designing
Girl Develop It Cincinnati: Intro to HTML/CSS Class 2
CSS Basics
Html basics
Html
Cascading Style Sheets (CSS) help
Complete Lecture on Css presentation
Frontend Crash Course: HTML and CSS
CSS Basics
Cascading Style Sheet (CSS)
Introduction to HTML and CSS
Basic html structure
HTML5
Html and css
HTTP Request and Response Structure
Web Page Designing Using HTML
Meta tags
 
Http
Html audio video

Viewers also liked

PDF
Basic Html Notes
PPTX
Php Tutorial
PPTX
Basic of PHP
PDF
M.c.a. (sem ii) operating systems
PDF
basic concept of php(Gunikhan sonowal)
PDF
M.c.a.(sem iii) operation research
PDF
MTP for MCA
PDF
MTP for MCA
PPTX
IgnouBCA
PDF
MTP for MCA
PDF
Web app development_cookies_sessions_14
PPTX
php tutorial - By Bally Chohan
Basic Html Notes
Php Tutorial
Basic of PHP
M.c.a. (sem ii) operating systems
basic concept of php(Gunikhan sonowal)
M.c.a.(sem iii) operation research
MTP for MCA
MTP for MCA
IgnouBCA
MTP for MCA
Web app development_cookies_sessions_14
php tutorial - By Bally Chohan

Similar to PHP HTML CSS Notes

PPTX
An Overview of HTML, CSS & Java Script
PPTX
AttributesL3.pptx
PPTX
Html
PPT
HTML & CSS.ppt
PPT
PPTX
Best Option to learn start here HTML.pptx
PPTX
Introduction to HTML-CSS-Javascript.pptx
PPTX
gdg Introduction to HTML-CSS-Javascript.pptx
PPT
html and css- 23091 3154 458-5d4341a0.ppt
PPTX
Introduction to Cascading Style Sheets .
PPT
html
PPTX
Introduction to HTML+CSS+Javascript.pptx
PPTX
Introduction to HTML+CSS+Javascript.pptx
PPTX
About html
DOCX
Lesson A.1 - Introduction to Web Development.docx
PDF
Girl Develop It Cincinnati: Intro to HTML/CSS Class 1
PDF
Punch it Up with HTML and CSS
PDF
Class Intro / HTML Basics
PDF
Html & Html5 from scratch
PPTX
HTMLforbeginerslearntocodeforbeginersinfh
 
An Overview of HTML, CSS & Java Script
AttributesL3.pptx
Html
HTML & CSS.ppt
Best Option to learn start here HTML.pptx
Introduction to HTML-CSS-Javascript.pptx
gdg Introduction to HTML-CSS-Javascript.pptx
html and css- 23091 3154 458-5d4341a0.ppt
Introduction to Cascading Style Sheets .
html
Introduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptx
About html
Lesson A.1 - Introduction to Web Development.docx
Girl Develop It Cincinnati: Intro to HTML/CSS Class 1
Punch it Up with HTML and CSS
Class Intro / HTML Basics
Html & Html5 from scratch
HTMLforbeginerslearntocodeforbeginersinfh
 

More from Tushar Rajput

PPTX
Unit 6 Privacy and Data Protection 8 hr
PPTX
Unit 5 Intellectual Property Protection in Cyberspace
PPTX
Unit 2 Regulation of Cyberspace
PPTX
Unit 1 Introducation
DOC
System analysis and_design
PPTX
Unit 4 Commerce and Cyberspace
PPTX
Unit 3 Cyber Crimes and Torts 8 hr
Unit 6 Privacy and Data Protection 8 hr
Unit 5 Intellectual Property Protection in Cyberspace
Unit 2 Regulation of Cyberspace
Unit 1 Introducation
System analysis and_design
Unit 4 Commerce and Cyberspace
Unit 3 Cyber Crimes and Torts 8 hr

Recently uploaded

PDF
M.Sc. Nonchordates Complete Syllabus PPT | All Important Topics Covered
PDF
DHA/HAAD/MOH/DOH OPTOMETRY MCQ PYQ. .pdf
PDF
Projecte de la porta de la classe de primer A: Mar i cel.
PDF
Analyzing the data of your initial survey
PPTX
Cost of Capital - Cost of Equity, Cost of debenture, Cost of Preference share...
PDF
BỘ TEST KIỂM TRA CUỐI HỌC KÌ 1 - TIẾNG ANH 6-7-8-9 GLOBAL SUCCESS - PHIÊN BẢN...
PDF
Projecte de la porta d'i5B: Els animals marins
PDF
Models of Teaching - TNTEU - B.Ed I Semester - Teaching and Learning - BD1TL ...
PPTX
Semester 6 UNIT 2 Dislocation of hip.pptx
PPTX
Basics in Phytochemistry, Extraction, Isolation methods, Characterisation etc.
PPTX
TAMIS & TEMS - HOW, WHY and THE STEPS IN PROCTOLOGY
PPTX
The Cell & Cell Cycle-detailed structure and function of organelles.pptx
PDF
IMANI Africa files RTI request seeking full disclosure on 2026 SIM registrati...
PDF
Digital Wellness in University Communities: Libraries as Guardians of Healthy...
PDF
Toward Massive, Ultrareliable, and Low-Latency Wireless Communication With Sh...
PPTX
AI_in_Daily_Life_Presentation and more.pptx
PPTX
PURPOSIVE SAMPLING IN EDUCATIONAL RESEARCH RACHITHRA RK.pptx
PPTX
Semester 6 unit 2 Atopic dermatitis.pptx
PPTX
York "Collaboration for Research Support at U-M Library"
PPTX
ELEMENTS OF COMMUNICATION (UNIT 2) .pptx
M.Sc. Nonchordates Complete Syllabus PPT | All Important Topics Covered
DHA/HAAD/MOH/DOH OPTOMETRY MCQ PYQ. .pdf
Projecte de la porta de la classe de primer A: Mar i cel.
Analyzing the data of your initial survey
Cost of Capital - Cost of Equity, Cost of debenture, Cost of Preference share...
BỘ TEST KIỂM TRA CUỐI HỌC KÌ 1 - TIẾNG ANH 6-7-8-9 GLOBAL SUCCESS - PHIÊN BẢN...
Projecte de la porta d'i5B: Els animals marins
Models of Teaching - TNTEU - B.Ed I Semester - Teaching and Learning - BD1TL ...
Semester 6 UNIT 2 Dislocation of hip.pptx
Basics in Phytochemistry, Extraction, Isolation methods, Characterisation etc.
TAMIS & TEMS - HOW, WHY and THE STEPS IN PROCTOLOGY
The Cell & Cell Cycle-detailed structure and function of organelles.pptx
IMANI Africa files RTI request seeking full disclosure on 2026 SIM registrati...
Digital Wellness in University Communities: Libraries as Guardians of Healthy...
Toward Massive, Ultrareliable, and Low-Latency Wireless Communication With Sh...
AI_in_Daily_Life_Presentation and more.pptx
PURPOSIVE SAMPLING IN EDUCATIONAL RESEARCH RACHITHRA RK.pptx
Semester 6 unit 2 Atopic dermatitis.pptx
York "Collaboration for Research Support at U-M Library"
ELEMENTS OF COMMUNICATION (UNIT 2) .pptx

PHP HTML CSS Notes

  • 1.
  • 2.
    2HTMLHTML is anot a scripting language or programming language.It is asimple markup language with the pair of markup tags.The first tag is known as opening tag (or) starting tag. The second tagis known as closing (or) end tag.HTML is used to describe the web pages.HTML can be written in notepad, notepad++, dream viewer, adov andcs5.HTML file can be saved with .html as its extension.The look end of an web page should be same on the all browsers. If itis not same the cross browser compatibility.Tags in html :Heading tags are h1, h2,h3,h4,h5,h6Ex: - <h1>welcome to html</h1>..<h6> welcome to html</h6><hr>: - this tag is used for horizontal line<br>: - this tag is used for break<p>: - this tag is used for paragraph content<b>: - this tag is used for bold content<i>: - this tag is used for italic content<link>: - this tag is used for connect the style sheets<script>: - this tag is used for JavaScript<big>: - this tag is used for big content
  • 3.
    3<strong>: - thistag is used for strong content<blink>: - this tag is used for blink content<del>: - this tag is used for delete the content<strike>: - this tag is used for strike<u>: - this tag is used for underline content<ins>: - this tag is used for insert content<q>: - this tag is used for quotation content<sup>: - this tag is used for super contentEx: - (a+b) <sup> 2</sup><sub>: - this tag is used for subscript contentEntities :Entities are used to describe the symbols (or) special characters on tothe web page. We have certain symbols are not available on thekeyboard. So such symbols can be inserting through entities. We havemainly two types of entities they are1. Named Entity2. Number Entity1. Named Entity :Syntax: - Ampersand + entity name + semicolonEx: -&dollar;2. Number Entity :Syntax: Ampersand + hash + ascci value+ semicolonEx : &#65; =>A&#153; =>Trademark: tm
  • 4.
    4List Tags :Listtags are two types1. Order list : Grouping of elements in the form of order wisethrough number, upper alpha (A),lower alpha (a), upper roman, lowerroman is known as order listEx: - Order list.html<ol type='a' start='25'><li>Nokia</li><li>Mototola</li><li>Sony</li></html>2. Unorder list : Grouping of elements in the form of disk, squarecircle are known as unorder listEx: -<ul type='square'><li>PHP</li><li>HTML</li></ul>Definition list : This is used to maintain the heading the descriptionon to the <dl> tag.Definition term : Definition term creates the headingDefinition description : Which holds the description of the content.Dt and dd tags are both child tags of DL.Ex :<dl><dt>Terms & Conditions</dt>
  • 5.
    5<dd><small><small>some large textmatter write here</small></small></dd></dl>Meta tag :Meta tag is used to generate the traffic on to your web page. Meta tagscan be embed into the head tag using Meta tag. Meta tag helps in search engine ranking on Google page andPTC(pay to click)Ex : Meta.html<html><head><title>Meta Tags</title><meta name='keyword'content='PHP,HTML,JQUERY,CSS,HYDERABAD,Institute,Ameerpet'/><meta name='description' content='We been in lamp for more than8years and trained many student ... many have got jobs in PHP ...'/><meta http-equiv='refresh' content='5;url=http://www.axis-bank.com'/></head><body><h2>We have changed our Website Name from UTI Bank to AXISBank ... Sorry for incontinent Please wait for 5 sec it would beAutomatically be Redirected</h2></body></html>
  • 6.
    6Link tags :Linksare used to navigate from one page to another page using inter(or) external links.The attributes we can pass areTarget = “-blank” // new web pageTarget = “-new” // new web pageTarget = “-self” // open on same pageLinks can target to mails and also search the link on same page.Ex : linktag.html<html><head><title>Link Tags</title></head><body><h3>Links Navigation</h3><a href='http://www.google.com' target="_blank">Google page</a> ||<a href='http://www.facebook.com' target='_self'>Facebook Page</a>||<a href='Tags.html' target="_new"> Tags Content</a></body></html>Image tags:Images can be embed into the body tag using image tag. Images haveextension of jpg, png, gif etc.,
  • 7.
    7Placing one imageon to the web page can be done by two types theyare1.Absolute Path2.Relative Path1. Absolute path : Working from the working directory you can callthe image from anywhere with respect to its parent directory (or) outof the parent directory (or) external files.Ex :<h2>absolute path</h2><img src = ‘http://www.google.com/images/mountain.jpg’ alt =‘beautiful’ border = ‘10’ width = ‘200px’ height = ‘180px;/>2. Relative path : Using relative path you can work with images onto the same current working directory (or) sub folders did not out ofyour parent directory.Ex :<h2>relation tags</h2><img src="suresh.jpg" width='140px' height='150px' border='0'title='suresh'/><br><img src="../water lilies.jpg" width='200px' height='180px' border='3'title='suresh'/><br><img src="../../sunset.jpg" width='200px' height='180px' border='3'title='suresh'/><br><img src="new folder/dsc_0083.jpg" width='200px' height='180px'border='3' title='suresh'/><hr>Tables create :Tables are used to put down content in tabular structure. Table tag canbe embed into your body tag using<table>
  • 8.
    8<tr> table row</tr><td>table data (or) content</td></table> The general attributes that we can pass in table tag areBorder = “<num>”Width = “<num>”Height = “<num>”Cellpadding = “<num>”Cellspacing = “<num>”Align= left/center/rightBackground = “image path”Fames = “box/group/lhs/rhs/above/below/vsides/hsidesRules = all/middle/bottomColspan =“<num>”Rowspan = “<num>”Bgcolor = “color name”Ex :<body><table border = “1” align = “center” width = “70%”><tr><td>employee detailsl</td></tr><table><tr><td>s.no</td><td>Name</td><td>designation</td></tr><tr><td>1</td><td>suresh</td><td>php programmer</td></tr></body>Cell padding : Cell padding is used to maintain the distance betweenits content and from its wall (or) borderCell spacing : Cell spacing is used to increase the wall (or) theborder
  • 9.
    9Frame set :Wecan divide the body into number of divisions that are passed as anargument based on rows (or) columns working with frame set youshould ensure that body tag is not givenNote : Frame set is a depreciated tag and would be working withfuture versionsEx :<frameset cols='30%,25%,*'><frame src = 'links.html' scrolling='no' ><frame src = 'entities.html' ><frame src = 'list.html' ></frameset>Iframes :Ex :<body><p align='center'><a href='list.html' target='x'>List Page</a> | <ahref='links.html' target='x'>Links Page</a><br><br><iframe src='list.html' name='x' width='600px' height='200px'></iframe></p></body>
  • 10.
  • 11.
    11Cascading Style Sheets(CSS)Cssstands for cascading style sheet. Css is used to put some styles(or) colors on to the web page. Css can be embed into the html headtag using style tag. There are mainly 3 different flavors to attach thisstyle on to the web page. Which are mainly1. Internal style sheet2. External style sheet3. In-line style sheet1. Internal style sheet :An internal style sheet should be used when a single document has aunique style. You define internal styles in the head section of anHTML 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>2. External style sheet :An external style sheet is ideal when the style is applied to manypages. With an external style sheet, you can change the look of anentire Web site by changing one file. Each page must link to the stylesheet using the <link> tag. The <link> tag goes inside the headsection:<head><link rel="stylesheet" type="text/css" href="mystyle.css" /></head>
  • 12.
    12An external stylesheet can be written in any text editor. The fileshould not contain any html tags. Your style sheet should be savedwith .css extension. An example of a style sheet file is shown below:hr {color:sienna;}p {margin-left:20px;}body {background-image:url("images/back40.gif");}3. In-line style sheet :An inline style loses many of the advantages of style sheets by mixingcontent with presentation. Use this method sparingly!To use inline styles you use the style attribute in the relevant tag. Thestyle attribute can contain any CSS property. The example shows howto change the color and the left margin of a paragraph:<p style="color:sienna;margin-left:20px">This is a paragraph.</p>We have one more style which is given by default by browsers whichis not editableExternal style sheet can be saved with .css as its extensionSyntax :(Attributes) element (or) class (or) id {property: value ;}CSS Syntax :A CSS rule has two main parts: a selector, and one or moredeclarations:The selector is normally the HTML element you want to style.Each declaration consists of a property and a value.
  • 13.
    13The property isthe style attribute you want to change. Each propertyhas a value.Selector :Selectors are identifiers which give styles based on elements, class(denoted by period ‘.’), id (denoted by ‘#’).We have 7 kinds ofselectors.They are : Element selector Class selector Class with element selector Id selector Id with element selector Attribute selector Pseudo selector1.Element selector :Ex : element.html<html><head><title>Element Selector</title><style>h1{color:green;}</style></head><body><h1>Welcome to my Website</h1></body></html>
  • 14.
    142.Class selector :Theclass selector is used to specify a style for a group of elements.Unlike the id selector, the class selector is most often used on severalelements.This allows you to set a particular style for many HTML elementswith the same class.The class selector uses the HTML class attribute, and is defined with" . (dot)"In the example below, all HTML elements with class="center" will becenter-aligned:3.Class with Element Selector :Example for Class Selector and Class with Element SelectorEx : class-selector.html<html><head><title>Class with Element Selector</title><style>h1{color:green;} //element selector.x{color:red;} // class selector//.x{font-family:impact;}p.x{font-size:20pt;color:black;} // Class with element selector</style></head><body><h1>Welcome to my Website</h1>
  • 15.
    15<h1 class='x'>This isnew Website </h1><h1>hello This is my next line</h1><p class='x'>Hello my next page</p><p>Rajesh</p></body></html>4.Id selector :The id selector is used to specify a style for a single, unique element.The id selector uses the id attribute of the HTML element, and isdefined with a "#".The style rule below will be applied to the element with id="para1":5.Id with Element Selector :Example for Id Selector & Id with Element SelectorEx : Id-selector.html<html><head><title>Id with Element Selector</title><style>h1{color:green;} //element selector.x{color:red;} // class selector//.x{font-family:impact;}p.x{font-size:20pt;color:black;} // Class with element selector#g{background:green;} //id selectorp#g{text-transform:uppercase;} //id with element selector
  • 16.
    16</style></head><body><h1>Welcome to myWebsite</h1><h1 class='x'>This is new Website </h1><h1>hello This is my next line</h1><p class='x'>Hello my next page</p><p class='x' id='g'>Rajesh</p><h2 class='x' id='g'>Amith</h2><h2 class='x' id='g'>David</h3><p class='x' id='g'>Praveen</p><p class='x' id='g'>Karthik</p></body></html>6.Attribute selector :Ex : attribute.html<html><head><title>Attribute Selector</title><style>.x{color:deeppink;font-family:impact;}
  • 17.
    17input[type='text']{color:deeppink;}</style></head><body>Name : <inputtype='text’ name='name' class='x'><br>username : <input type='text' name='uname'><br></body></html>7.Pseudo selector :Ex : pseudo.html<html><head><title>Pseudo Selector</title><style>p:first-letter{font-size:30pt;color:deeppink;font-family:arial black;}p:first-line{color:orange;}
  • 18.
    18</style></head><body><p>This is myfirst email to all you guys his is my first email to allyou guys his is my first email to all you guys his is my first email toall you guys his is my first email to all you guys</p></body></html>Css cheat sheet :Font-styles :font-style : italic,normalfont-variant : small-caps,narmal,small,caps(capital letters)font-weight : normal,lighter,bold, bolder, number(100->light,900->bolder)font-size : <num> px;font-family : family of fontText properties :1. letter-spacing : <num>px2. word-spacing : <num>px3. line-height : <num>px4. text-align : left/center/right/justify ->order from left (or) right5. text- decoration : name, blink,underline,overline,line-through6. text-transform : capitalize(upper case/lower case(everythingconvert))7.text-indent : <num>px (distance from line to first letter)
  • 19.
    19 The text-alignproperty is used to set the horizontal alignment ofa text. Text can be centered, or aligned to the left or right, orjustified. When text-align is set to "justify", each line isstretched so that every line has equal width, and the left andright margins are straight (like in magazines and newspapers). The text-decoration property is used to set or removedecorations from text. The text-decoration property is mostlyused to remove underlines from links for design purposes: The text-transform property is used to specify uppercase andlowercase letters in a text.It can be used to turn everything intouppercase or lowercase letters, or capitalize the first letter ofeach word. The text-indent property is used to specify the indentation of thefirst line of a text.Background property :CSS background properties are used to define the background effectsof an element.background-color : ‘color name’;background-image : url(image path name);The background-image property specifies an image to use as thebackground of an element.By default, the image is repeated so it covers the entire element.The background image for a page can be set like this:background-repeat : no-repeat,reapt-x,reapt-y,repeat(*);By default, the background-image property repeats an image bothhorizontally and vertically.Some images should be repeated only horizontally or vertically, orthey will look strange, like this:background-attachment : fixed,scroll;
  • 20.
    20background-position :{x,y}left,center,right,bottom,topWhen usinga background image, use an image that does not disturbthe text.Showing the image only once is specified by the background-repeatproperty://background : order wiseList properties :list-style-type : none,disk,circle,square,decimal,upper-alpha,lower-alpha,upper-roman,lower-roman;list-style-position : outside (*) / inside;list-style-image:url(image path name);Box properties :Padding : inside elementMargin auto = centerOverflow = visible (*), hidden, auto, scrollEx :<html><head><title>BOX properties</title><style>//body{margin:0px;}p{text-align:center;}.z{background:#ccc;padding:15px;
  • 21.
    21width:50%;height:80px;margin:auto;overflow:auto;text-align:justify;}</style></head><body><p><input type='checkbox' name='t&c'/>Terms & Conditions<p class='z'>Some large text matter</p></p></body></html>Border Properties :border-width : <num>px;border-style : solid,groove,inset,outset,double,dotted,dashed;border-color : <color name>//border: order wiseDiv tag :Div tag stands for division tag.Div tag is the block level element. Ablock level element creates a block with coming left and right breaksin it.
  • 22.
    22Ex : divtag, p tag, h1 to h6, table tag, ul and li tagsIn-line element : These particular elements will take the contentspan only and does not have breaks initSpan tag is the natural tag.Ex :<html><head><title>in-line element</title><style>h1 {background : green; display : inline;}b{Background: gold;}a.{text-align : center; background : yellow; display : block;}</style></head><body><h1>hello</h1><b>hello</b><i>hello</i><p>hello</p> <hr><span class = ‘a’>hello</span><div class = ‘a’>hello</div> <hr><h3> converting block & inline & respectively<h3><h1> hello</h1>
  • 23.
    23</bold></html>Display properties :Visibility: we have visible (or) hiddenDisplay : none, in-line, block;Padding : <num>px all sidesPadding : top left0px 0pxBottom rightMargin : <num> all sidesMargin : top right bottom left0px 0px 0px 0pxTemplates :Position properties : Position in css we have absolute, relative andfixed positionRelative position : Working from the current position we can movethe element anywhere on to the web page but cannot be moved on thetop of the position place.Absolute & fixed position : Placing from the current position wecan move the element to all corner of the web page and also one topof the position place .once an element declare as fixed (or) absolutethis will turn to in-line element and this will also carry ‘7’ index initEx : position.html<html><head><title>Position properties</title>
  • 24.
    24<style>div{background:blue;color:#fff;font-size:17pt; font-weight:bold;padding:10px;margin:4px;}.r{background:gold;color:#000;position:relative;left:30px;top:120px;}.a{background:blue;position:absolute;top:50px;left:6px;}.f{background:deeppink;color:#000;position:fixed;bottom:0px;right:0px;}</style></head><body><div>Normal Position</div><divclass='a'>Absolute Position</div><div class='r'>Relative Position</div><div class='f'>Fixed Position</div><h1>some large text matter </h1><h1> some large text matter </h1><h1> some large text matter </h1><h1> some large text matter </h1></body></html>
  • 25.
  • 26.
    26JavaScript JavaScript isclient side scripting language. JavaScript is the case sensitive. JavaScript can be used for AJAX integration and validation. JavaScript can be embed into the head tag and body tag usingscript tag. JavaScript can be saved with .js as its extension.Content: Variables Datatypes Operators (Assignment, Arthamatic, Post/Pre [Inc/Dec],Comparission, Relational, Conditional, Logical,Ternary) Alert,prompt,confirm Built in Functions (Arrays,Date,Math,String) DOM (Document Object Module) Navigator,images,screen,location,history Document – (getElementById, getElementsByTagName,getElementsByName) Events : General Events (onclick(), ondblclick(), onload(),onunload(), onreset(), onsubmit(), onfocus(), onblur(),onchange()) Mouse Events (onmouseover(), onmousemove(),onmousedown(), onmouseout() ) Key Board Events – (onkeyup() , onkeydown() )Document.write () :document.write is the printing method in javascript.Which is outputstatement to the browser.Ex: first.html<html><head>
  • 27.
    27<script src='ext.js' type='text/javascript'language='javascript'></script><script>document.write('Thisis Called from Head Tag<br>');</script></head><body><h1>Welcome</h1><script>document.write('This is Called from Body Tag<br>');</script></body></html>ext.js:-document.write('<h1>This is called from External Page</h1>');Variables :Variables are case sensitive. Declaring a variable in JavaScript asvariable name = value;Variables are "containers" for storing information.Ex : var a = 10; var = defaultThe correct method to declare are :Var a = 10;Var_a = 10;Var first-name = ‘suresh’;
  • 28.
    28Var firstName =‘suresh’;Var $name = ‘suresh’;Wrong method :Var #name = ‘suresh’;Var 1a = 10;Var first name = ‘suresh’;Data Types :String :Collection of characters inside a single (or) double quotations areknown as string ,working with single quotation and adding doublequotation in it is valid.But adding single quotation inside a singlequotation is not valid.Ex : datatypes.html<html><head><script>var a = 10;document.write('<h1>'+a);document.write(' - ');document.write(typeof(a));document.write('<br>');var f = 10.25;document.write(f);document.write(' - ');document.write(typeof(f));
  • 29.
    29document.write('<br>');firstname = 'Rajesh';document.write(firstname+'- '+typeof(firstname)+'<br>');firstname = firstname+' Kumar';document.write(firstname+' - '+typeof(firstname)+'<br>');firstname += 'B';document.write(firstname+' - '+typeof(firstname)+'<br>');document.write('<hr>String Methods<hr>');document.write('i'll Pay the Bill Tomorrow');</script></head><body><h1>Welcome</h1></body></html>Operators :1.Assignment operator: ‘ = ‘ is used to assign values.The assignment operator ‘=’ is used to assign values to JavaScriptvariables.Ex :<script>document.write('<h1 align="center">Assignment Operator</h1>');var x = 10;
  • 30.
    30document.write("The Value is: "+x);</script>2.Arithmetic operator: -The arithmetic operator ‘ +’ is used to add values together.Arithmetic operators are used to perform arithmetic between variablesand/or values.Ex :<script>document.write('<h1 align="center">Arthamatic Operator</h1>');a = 5; b = 3;document.write("Addition : "+(a+b)+'<br>');document.write("Multiplication : "+(a*b)+'<br>');document.write("Division : "+(a/b)+'<br>');document.write("Minus : "+(a-b)+'<br>');document.write("Modulus : "+(a%b)+'<br>');</script>3.Comparision operator :Comparision operators are used in logical statements to determineequality or difference between variables or values.Ex :<script>Document.write('<h1 align="center">comparision Operator</h1>');if(10 != '10'){
  • 31.
    31document.write('<h2>Correct</h2>');} else {document.write('<h2>NotCorrect</h2>');}document.write('<h1 align="center">Post & Pre Increment</h1>');m = 10;n = (m++)+(++m)+(m++)+(++m);document.write('The Value of m is : '+m+'<br>The Value of n is :'+n+'<br>');</script>4.Relational operator : < , > , <= , >=5.Logical operator : &&(and) -- ||(or)6.Ternary operator :Syntax for Ternary Operator :Var a= 10;Type = (a%2 == 0)? ‘even number’: ‘odd number’;//document.write(“the value you entered is : ”+type);document.write(type);Conditions :1.If else :Whenever a condition is ‘if’ it is true that part of the constructor willbe excuted.if condition is fail ‘else’ part would get executed.
  • 32.
    32 Conditional statementsare used to perform different actionsbased on different conditions use this statement to execute some code if the condition is trueand another code if the condition is falseSyntax :If (cond){//code}else{// code};2.If else if :if else if (or) ladder condition will take more than one condition (or)multiple conditions. If all the conditions fail in if else if constructorthen only else part get executed Use this statement to select one of many blocks of code to beexecutedSyntax :If(cond){//code}
  • 33.
    33else if (cond){//code}elseif (cond){//code}..else{//default value;}3.Switch :Use the case in-order wise. This is main concept in switch case Use this statement to select one of many blocks of code to beexecuted Conditional statements are used to perform different actionsbased on different conditions.Syntax :switch(n){case 1: execute code block 1
  • 34.
    34break;case 2: executecode block 2break;default:code to be executed if n is different from case 1 and 2}Looping methods :While:do-while:Syntax:Syntax:Initialize methodInitializeWhile (cond)do{{//code//code}}1.While :Working with while loops it will first check the initialize part andchecks the condition. If condition is true it will get into theconstructor and takes place until condition fail and comes out of theconstructor. loops through a block of code while a specified condition is true
  • 35.
    352.Do-while :This willalso checks the initialized part .but for only first time it willget into the constructor and execute the code and checks theconditions later and if condition is true looping takes place (or) else itcome out of the constructor with at least single time execution code3.For-loop :For loop first initialize condition an inc/dec will be done on same(single) line for the every first time it will initialize with part themcheck within condition if condition is true the constructor will getexcuted.condition fail will come out of the for loop (constructor) Loops execute a block of code a specified number of times, orwhile a specified condition is true.Syntax :For (initialize; condition; inc/dec ){//code}Arrays :A variable which can hold more than one value is none as array (or)super variable as array can be defined is JavaScript asVar a = new Array (values); // a->super variable To find the length of the array we can go with length = arrayname.length; If the array index is been initialize more than the currentindex++ then memory is wasted in JavaScript In arrays initializing string index the printing method will notwork in JavaScriptNote : - document.write() (or) looping method will not able to printstring indexes
  • 36.
    36 While, do-while, for-loop will not print string indexes inJavaScript so to print string indexes we can go withSyntax: - for (var name in Array name) For is key word in JavaScript which will print the string index The Array object is used to store multiple values in a singlevariable. An array is a special variable, which can hold more than onevalue, at a time.Create an Array :An array can be defined in three ways.The following code creates an Array object called myCars:1: var myCars=new Array(); // regular array (add an optional integermyCars[0]="Saab"; // argument to control array's size)myCars[1]="Volvo";myCars[2]="BMW";2: var myCars=new Array("Saab","Volvo","BMW"); // condensedarray3: var myCars=["Saab","Volvo","BMW"]; // literal arrayEx : Array.html<script>var a = new Array(10,20,30,40);document.write('The Array is : '+a+'<br>');document.write('Length of Array : '+a.length+'<br>');document.write('Index at 2 : '+a[2]+'<br>');a[2] = a[2]*2;document.write('The Array is : '+a+'<br>');a[4] = 'New Value';
  • 37.
    37document.write('The Array is: '+a+'<br>');var b = new Array();b[0] = 100;b[1] = 200;b[2] = 300;b[3] = 400;b['Name'] = 'Rajesh';b['Age'] = 30;b[7] = 700;b[10] = 1000;document.write('<hr>Single string Index : '+b['Name']+'<hr>');document.write('The Array is : '+b+'<br>');for(i=0;i<b.length;i++){document.write('Index at : '+i+' = '+b[i]+'<br>');}document.write('<hr>');for(c in b){document.write(c+' = '+b[c]+'<br>');}document.write('<hr>');var d = [10,20,30];document.write('The Array in d is : '+d+'<br>');document.write('The Array in d is : '+d.length+'<br>');document.write('<hr>');
  • 38.
    38var e ={'Name':'Rajesh','Age':30,10:20,'Status':'Active'};document.write('The Array in d is : '+e+'<br>');for(i=0;i<e.length;i++){document.write('Index at : '+i+' = '+e[i]+'<br>');}for(c in e){document.write(c+' = '+e[c]+'<br>');}</script>Double dimensional array:An array can have more than one array is called double dimensionalarray.Ex : douledimensionarray.html<html><head><script>var a =[[1,'Ajay',[45,62,49,72,55,84]],[2,'Rajesh',[48,62,94,72,38,62]],[3,'Suresh',[48,63,82,97,45,28]]];//document.write(a[1][1]);document.write('Name is : '+a[2][1]);document.write("<table border='1' align='center' width='60%' >");document.write("<tr><th colspan='9'>Student Marks Memo Report</th> ");
  • 39.
    39document.write("<tr><td rowspan='2'>Roll No</td><tdrowspan='2'>Name</td><td colspan='6'align='center'>Subjects</td><td rowspan='2'>Pass/Fail</td></tr>");document.write("<tr><td>English</td><td>Hindi</td><td>Telugu</td> <td>Maths</td><td>Science</td><td>Social</td></tr>");document.write("<tr><td>"+a[0][0]+"</td></tr>");</script></head><body><tr><td><script>document.write(a[1][0]);</script></td><td><script>document.write(a[1][1]);</script></td></tr></table></body></html>Array built-in Functions :Join : Join is the pre-defined key-word in the JavaScript .which willconvert the given array into the separator passed default separator iscoma (,).Concat : concat is joining more than array in single array is calledconcat.Reverse : reverse in JavaScript the array last being is first. First islast without (descending order) the original array will also getaffected. If we use reverse function.Sort : sort is nothing but given the order is ascending order .Unshift : unshift will add the value at the starting of the array. Thevariable use for unshift will holds the length of the array and theoriginal array would get affected.
  • 40.
    40Shift : shiftfunction will not hold any arguments should will removethe starting value of the array.The variable unshift will hold theremoved value.Push : push is nothing but insert the value into the array at the end ofarray is called push.Pop : pop is nothing but remove the last value in the array is calledthe pop.Ex : arraybuiltin.html<script>var a = new Array('This','is','my','new','car');document.write('The Original Array is : '+a+'<br>');b = a.join(' ');document.write('Join Method : '+b+'<br>');var a = new Array(10,20,30);var b = new Array(40,50);var c = new Array(60,70,80);document.write("Concat Two Arrays : "+a.concat(b)+"<br>");document.write("Concat All Given Array : "+a.concat(b.concat(c))+"<br>");var a = new Array('Ajay','Raju','Amith','Zebra','Arjun');b = a.reverse();document.write("Reverse of an Array : "+b+'<br>');document.write("Original Array : "+a+'<br>');var a = new Array('Ajay','Raju','Amith','Zebra','Arjun');b = a.sort();document.write("Assending Order : "+b+'<br>');
  • 41.
    41document.write("Original Array :"+a+'<br>');b = a.reverse();document.write("Reverse With Desending Order : "+b+'<br>');document.write("Original Array : "+a+'<br>');var x = new Array(10,20,30);b = x.unshift(5);document.write("Unshift Method : "+x+'<br>');document.write("The Value Stored in B : "+b+'<br>');var x = new Array(5,10,20,30);b = x.shift();document.write("shift Method : "+x+'<br>');document.write("Removed Value is stored B : "+b+'<br>');var x = new Array(5,10,20,30);b = x.push(40);document.write("Push last Value to Array Method : "+x+'<br>');document.write("B holds the length of the Array: "+b+'<br>');var x = new Array(5,10,20,30);b = x.pop();document.write("Pop Removes last Value in Array : "+x+'<br>');document.write("B holds the Removed Value: "+b+'<br>');</script>Functions:-Functions in javascript are case sensitive once declare a functionname and try to re-declare. The same function name will overwriteprevious function name. Functions are used to debug the code and
  • 42.
    42analize the errorseasily. Working with length of the code will bereduced.We have mainly 4 types of the functions in JavaScript that is1. Function without arguments and return value2. Function with arguments and no return value3. Function with return value and no arguments4. Function with arguments and return valueSyntax :Function function name (arguments, arg){//code}1. Function without arguments and return valueEx :<script>test();function test(){document.write('This is Function without Aurgument<br>');document.write('This is my function Content<br>');}function test1(){document.write('Overwritten is done on the previous printingmethods<br>');}test();
  • 43.
    43test();</script><body><script>test();</script></body>2. Function witharguments and no return valueEx :<style>.error{background:gold;color:green;padding:10px;margin:auto;width:60%;font-size:18pt;}.success{background:black;color:#fff;padding:10px;margin:auto;width:60%;font-size:18pt;}</style><script>function welcome(name){document.write("Welcome ! "+name+'<br>');}welcome('Rajesh');welcome('Amith');function statement(type,message){document.write("<div class='"+type+"'>"+message+"</div>");}//statement("error","Welcome Guest ! ");
  • 44.
    44statement("success","Welcome Rajesh");</script>3. Functionwith return value and no argumentsEx :<script>function test(){document.write('This is line 01<br>');document.write('This is line 01<br>');return 10 2;document.write('This is line 01<br>');document.write('This is line 01<br>');}test();var x = test();document.write('The Value in x is : '+x+'<br>');</script>4. Function with arguments and return valueEx :<script>function square(num){return num*num;}document.write('The Square root of 5 is : '+square(5)+'<br>');document.write('The Square root of 5 is : '+square(square(5))+'<br>');
  • 45.
    45</script>Math built-in function:In JavaScript we have mainly seven kinds of math objects which arepre-defined and can be called respective key-words. Which areincluded in JavaScript library.Ex : math.html<script>function r(txt){document.write('<h2>'+txt+'</h2>')}r("<u>Javascript Predefined Math Constant Object </u>");r('Eulers Constant : '+Math.E);r('Pi Value : '+Math.PI);r('SQRT OF 2 : '+Math.SQRT2);r('Natural Log 2: '+Math.LN2);r('Natural Log 10 : '+Math.LN10);r('Log base 2 of Eulers : '+Math.LOG2E);r('Log base 10 of Eulers : '+Math.LOG10E);r("<u>Javascript User - defined Math Object </u>");r('Max Value : '+Math.max(10,20,30));r('Min Value : '+Math.min(10,20,30));r('Sqrt Value : '+Math.sqrt(25));r('2 pow 4 : '+Math.pow(2,4));r('Absolute Value : '+Math.abs(-9));
  • 46.
    46r('Ceil Value :'+Math.ceil(2.11111));r('floor Value : '+Math.floor(2.9999));r('round Value : '+Math.round(2.5111111));r('Random Number : '+Math.random());r('Number Between 1 to 1000 : '+Math.round(Math.random()*1000));</script>String built-in functions :Ex : stringbuilt.html<script>function r(txt){document.write(txt+'<br>');}var str = "lamp Institute";r('String Value = '+str);r("Length of the String = "+str.length);r("Color of String = "+str.fontcolor('green'));r('Upper Case = '+str.toUpperCase());r('Lower Case = '+str.toLowerCase());r('Big Font = '+str.big());r('Bold Font = '+str.bold());r('Small Font = '+str.small());r('Italic Font = '+str.italics());r('Superscript = '+str.sup());r('sub script = '+str.sub());
  • 47.
    47r('<hr><h2><u>Slice Function([begin, stop])</u></h2>');r('Slice(4) = '+str.slice(4));r('Slice(4,8) = '+str.slice(4,8));r('Slice(-9) = '+str.slice(-9));r('Slice(-9,8) = '+str.slice(-9,8));r('Slice(-9,-3) = '+str.slice(-9,-3));r('<hr><h2><u>Substring Function([From, to]) </u></h2>');r('substring(4) = '+str.substring(4));r('substring(4,8) = '+str.substring(4,8));r('substring(4,2) = '+str.substring(4,2));//r('substring(-9) = '+str.substring(-9));r('<hr><h2><u>substr([start, length]) </u></h2>');r('substr(4) = '+str.substr(4));r('substr(5,8) = '+str.substr(5,8));r('substr(-9) = '+str.substr(-9));r('substr(-9,2) = '+str.substr(-9,1));r('CharAt(0) = '+str.charAt(1));r('charCodeAt(1) = '+str.charCodeAt(1)); //ascill Value of Indexmob = 'Z123456789';r('charCodeAt = '+mob.charCodeAt(0));r('Indexof = '+str.indexOf('T'));//-1r('lastIndexof = '+str.lastIndexOf('t'));r('indexOf = '+str.indexOf('t',9));r('Search = '+str.search('z'));//-1
  • 48.
    48r('Match = '+str.match('z'));//null</script>Mobilefunction :Ex : mob.html<script>function r(txt){document.write(txt+'<br>');}mob = "8855644045";r(isValidMobile(mob));function isValidMobile(val){if(val.length != 10){return "Please Enter 10-Digit Mobile Number";}f = val.charAt(0);if(f == '7' || f == '8' || f == '9'){} else {return 'Please Check the First Digit of Number & tryAgain';}return isNumeric(val);}function isNumeric(val){for(i=0;i<val.length;i++){
  • 49.
    49ascii = val.charCodeAt(i);if(ascii< 48 || ascii >57){return 'Only Numbers Allowed Please Check again';}}return 'Valid Mobile Number';}</script>Date functions: -Date function can be defined with variable is equal to new date. Thisfunction is pre-defined in JavaScript which will explain the systemtiming (or) running the domain it will capture the running domain.Get time () : This is unique time constant which is created findgenerate number of milliseconds right from night jan 1st 1970.Ex : date.html<script>function r(txt){document.write(txt+'<br>');}var d = new Date();r('The value in d is : '+d);r('Unix Time Constant that is Midnight Jan 01,1970 (no ofmillseconds : ) '+d.getTime());r('Date : '+d.getDate());r('Day : '+d.getDay());
  • 50.
    50r('Month : '+(d.getMonth()+1));//0 -11r('Year : '+d.getYear());//works only in ie...r('FullYear : '+d.getFullYear());r('Hours : '+d.getHours());r('Minutes : '+d.getMinutes());r('Seconds : '+d.getSeconds());r('Time is : '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());</script>DOM :DOM contains these layers1.IMAGES2.LOCATIONS3.SCREEN------------------> Get Element ById4.DOCUMENTS-----------> GetElementByTagName5.NAVIGATOR------------ > GetElementByName6.EMBEDEx : dom.html<script>function dochange(){document.testForm.fname.value = alert("Please Enter");document.testForm.fname.value = 'Enter Name';document.testForm.lname.style.border="2px solid red";document.testForm.lname.style.width="200px";}
  • 51.
    51</script><body><form name='testForm'>First Name: <input type='text' name='fname' /><br>Last Name : <input type='text' name='lname'/><br><input type='button' name='change' value='DoChange'onclick="#"https://www.slideshare.net/slideshow/php-html-css-notes/70397758#52">52</form></body>GetElementByTagName :This particularfunction will match tag name and excute the functionwhich we are passing as a tag nameEx : getElementsByTagName.html<script>function dochange(){var a = document.getElementsByTagName('div');for(i=0;i<a.length;i++){a[i].style.width = '400px';a[i].style.background = '#ddd';a[i].style.border = '4px dotted green';}}</script><body onmouseover='dochange();'><h1>Welcome to My Web Page</h1><p>This is my First Page</p><p>This is my First Page</p><p>This is my First Page</p><p>This is my First Page</p><div>What is Social Hub</div></body>
  • 53.
    53GetElementByName :This particularfunction will match element name and that part of thefunction will get excutes.Ex : getElementsByName.html<script>function dochange(){var a = document.getElementsByName('x');for(i=0;i<a.length;i++){a[i].style.width = '400px';a[i].style.background = '#ddd';a[i].style.border = '4px dotted green';}}</script><body onmouseover='dochange();'><h1>Welcome to My Web Page</h1><p>This is my First Page</p><p>This is my First Page</p><p>This is my First Page</p><p>This is my First Page</p><div>What is Social Hub</div></body>Note 1 : As ids are unique we have singular matching so we cangetElementById as singular.
  • 54.
    54Note 2 :GetElementByTagName & ByName works the array formatand these are plural.Events :Whenever an event is trigger and then that particular matchingfunction will excuted.a)innerHTML : innerHTML is used to push the dynamic values onto the HTML page.b)set Interval : setInterval is pre-defined key-word in JavaScriptwhich takes 2 arguments the first argument can be expression (or)function the second argument can be number of milliseconds.c)Alert : Alert gives you a single button option until it is click It willallowed you to navigate on the server.Ex : alert.html<script>alert("Please Agree with Our Terms & condition");</script><body>Welcome</body>d)Confirm : Confirm is used two options until something is beingclick. It won’t allowed to navigate the server and if it is click based onthe values it will moved to the respect pages.Ex : confirm.html<script>var x = confirm("Are You legally 18+ then enter to site");if(x == true){document.write("Welcome to my Terrorist Site");
  • 55.
    55} else {document.write("ThankYou for leaving Please <ahref='http://www.google.com'>Click Here</a>");}</script><body></body>e)Eval : Eval is pre-defined function in JavaScript which willevaluate the given function in between the JavaScript (function)f)parseINT : This is pre-defined function in JavaScript which willconvert the floating value into integer value.g)parseFLOOT : This is pre-defined function in JavaScript whichwill convert the integer value into floating value.Ex : innerHTML & set Interval time.html<script>function r(txt){document.write(txt+'<br>');}function currTime(){var d = new Date();var time =timeFormat(d.getHours())+':'+timeFormat(d.getMinutes())+':'+timeFormat(d.getSeconds());return 'Present Time : '+time;}function timeFormat(val){return ((val<10)?'0':'')+val;
  • 56.
    56}function writeTime(id){return document.getElementById(id).innerHTML= currTime();}</script><body><div id='currentTime' align='right'><script>r(currTime());setInterval("writeTime('currentTime')",1000);</script></div></body>
  • 57.
  • 58.
    58PHP Rasmus Lerdorfis the founder of the PHP in 1995. PHP is the server side scripting language. Php needs a server to excute the file. Php files should be saved with .php as its extension ".php3", or".phtml" Or else our server will not excute unknown extension apart from.html, .cpi, .cgs, Php supports all the data bases that are present in the marketEx:-mySql,mssql,infonix,Sybase,ibmdb2,postgresql………etc Php can be worked on all the operating systems that iswindows,linux,max,solaries…etc Php can communicate with different serversEx:-SMTP(Simple mail transfer protocal), imap (internet maxaccess protocal), LDAP, Informix, Oracle, Sybase, Solid,PostgreSQL PHP can be install as a software tags we get many of the serverfilesEx : Xampp, Wamp, easy php, mamp PHP stands for PHP: Hypertext Preprocessor PHP is an open source software PHP is free to download and use PHP is easy to learn and runs efficiently on the server sideXampp : Xampp stands forx------------------------>platform(windows,linux,mac,solaries)a------------------------->apache(web server)m------------------------>mysql(database file)p------------------------->perl(perl scripting in php)p------------------------->php/my admin (web database tool)php current version is 5.3.8
  • 59.
    59Wamp : Wampstands forw------------------------>window exva------------------------>apache(web server)m------------------------>mysql(database file)p------------------------>php/my admin (web database tool)Mamp : Mamp stands form------------------------>mac ‘os’a------------------------->apache(web server)m------------------------>mysql(database file)p------------------------->php/my admin (web database tool)Apache contain the 1-65535 ports.In that 1-1024 are pre-reservedports.Tmp : Tmp holds session details & temp upload files.Htdocs : After installing xampp we have to store our files into thefolder called htdocs. Once files are saved in htdocs we can open withthe location path ashttp://localhost/abc(foldername)/first.phpEcho : echo is the output method in php.Basic PHP Syntax :<?phpecho “universal way of writing php<br>”;?><script language = ‘php’>
  • 60.
    60echo “javascript wayof writtting php<br>”;</script><?echo”short tag way of writing php<br>”;?><%1echo “asp way of writing php<br>”;%>Comments in PHP :In PHP, we use // to make a one-line comment or/* and */ to make a comment block<html><body><?php//This is a comment/*This isa commentblock*/?></body></html>
  • 61.
    61Printing methods inphp :a.Echo : echo is an argument can print multiple arguments. Echo as afunction can print only one argument.b.Print : print is an argument can print only one argument.print also afunctionEx: - print”arg<br>”;c.Printf : printf will take formatting string with respected values asprintEx : printf(“(int%d) (float%f) (string %s) (asci%c)”);d.Print-r : print-r will print array of stringEx: - $g = array (10,20,30,true,’kalam’);Print-r($g);e.Var-dump : It is also printing method which is used debugging theerrors very easily. This not used in production level (liveenvironmental )Ex : var-dump($g);<h1>Printing Methods in PHP</h1><?php$a = 10; $b = 20; $c = 30;echo "Arg01","Arg02","Arg03<br>";echo $a,$b,$c,'<br>';echo ("Arg01<hr>");print "Arg01<br>";print("Arg01<hr>");
  • 62.
    62printf("(int %d) (float%.2f)(string %s) (Ascii %c)",22.25,10.2545,'Rajesh',97);echo '<hr>';$g = array(10,20,30,true,'Rajesh');print_r($g);echo '<hr>';var_dump($g);?>Controlling :Ex : controlling.php<style>b{color:green;}</style><?phpecho "line 01<br>";echo "line 02<br>";echo "line 03<br>";?><b>This is Bold Tag</b><hr><?phpif(false){echo "<b>The 1<sup>st</sup> is Executed<br></b>";} else {echo "<b>The 2<sup>nd</sup> is Executed<br></b>";
  • 63.
    63}?><hr><h2>Alternate Method</h2><?phpif(true){?><b>The 1<sup>st</sup>is Executed<br></b><?php}else{?><b> The 2<sup>nd</sup> is Executed<br></b><?php}?>Variables : Variables are "containers" for storing information. Variables in PHP starts with a $ sign, followed by the name ofthe variable. The variable name must begin with a letter or the underscorecharacter. A variable name can only contain alpha-numeric characters andunderscores (A-z, 0-9, and _). A variable name should not contain spaces.
  • 64.
    64 Variable namesare case sensitive (y and Y are two differentvariables).Ex : variables.php<h1>Variables in php</h1><?php$a = 10;$name = 'Rajesh';$_name$_name$n123$_1232$1_name$first_Nameecho 'The Value is : ',$a.'<br>';echo 'The Name is : ',$name,'<br>';?><script>var a = 15;document.write('The Value of a is : '+a+'<br>');</script> In PHP, a variable does not need to be declared before adding avalue to it.
  • 65.
    65 In theexample above, notice that we did not have to tell PHPwhich data type the variable is. PHP automatically converts the variable to the correct data type,depending on its value. In a strongly typed programming language, you have to declare(define) the type and name of the variable before using it.PHP has four different variable local global static Super global array variableLocal variable : A variable declared within a PHP function is localand can only be accessed within that function.Ex : localvariable.php<?phpfunction test(){$a = 10;echo 'The Value of $a inside function is : ',$a,'<br>';}test();echo 'The Value of $a Outside Function is : ',$a,'<br>';?>Static variable : When a function is completed, all of its variablesare normally deleted. However, sometimes you want a local variablenot to be deleted.To do this, use the static keyword when you first declare the variable.
  • 66.
    66Ex : staticvariable.php<?phpfunctiontest(){$a = 10;static $b = 20;echo 'The Value of $a inside function is : ',$a,'<br>';echo 'The Value of $a inside function is : ',$b,'<br>';$a++;$b++;}echo 'The Value of $b outside is : ',$z,'<br>';test();test();?>Global variable : Global scope refers to any variable that is definedoutside of any function.Global variables can be accessed from any part of the script that is notinside a function.To access a global variable from within a function, use the globalkeyword:Ex : global.php<?php$x = 10;
  • 67.
    67echo 'The Valueof $x = ',$x,'<br>';function test(){//global $x;echo 'The Value of $x inside Function = ',$x,'<br>';echo '$GLOBALS["x"] = ',$GLOBALS['x'],'<br>';}test();?>Super global array variable : ‘$ global’ is the super global arrayvariable. This is the pre-defined keyword. In php we have mainlysome of the super global variables. This can be used with theirkeywords.i) $_EVN : This is used for getting the information of your operatingsystem ($_ENV (PATH))ii) $_SERVER : This will give you the information about yourserver(apache information)iii) $_GET : It is used for form processing through get method (or)query stringiv) $_POST : This is used for form processing through post methodin secure mannerv) $_REQUEST : It will send the form through both get and post andcookievi)$_COOKIE : This is used to get the information about the browserwho is using the web(computer)vii)$_SESSION : It is used to get the information of the user inbetween login and logout details are store at server machine.
  • 68.
    68Operators :1. Assignmentoperator: = is used to assign values to variables inPHP2. Arithmetic operator: +,-,/,*,%3. Increment & decrement operator: i++,++I & i--, --i4. Comparison operator: ==,!= ,===5. Relational operator: <=, >=, <>6. Logical operator: &&, ||, and, or7. Error handling operator :8. Scope resolution & this operator : ::----->scope, &------->thisEx : operator.php<?phpecho '<h1 align="center">Assignment Operator</h1>';$a = 10;echo 'The Value is : '.$a.'<br>';echo 'The Value is Added by 2 : ',$a += 2,'<br>';$name = 'Rajesh';echo 'My name is : '.$name,'<br>';$name .= ' Kumar';$name = $name.' Kumar';
  • 69.
    69echo 'My nameis : ',$name,'<br>';echo '<h1 align="center">Arthamatic Operator</h1>';echo 'The value of 2+3 : ',2+3,'<br>';echo 'The Value of 2-3 : ',2-3,'<br>';echo 'The Value of 2/3 : ',2/3,'<br>';echo 'The Value of 2*3 : ',2*3,'<br>';echo 'The Value of 2%3 : ',2%3,'<br>';echo '<h1 align="center">Increment & Decrement [INC/DEC]</h1>';echo '<h2>POST & PRE increment</h2>';$x = 10;echo 'The Value of $x = ',$x,'<br>';echo 'The Value of $x++ = ',$x++,'<br>';echo 'The Value of $x = ',$x,'<br>';echo 'The Value of ++$x = ',++$x,'<br>';echo 'The Value of $x = ',$x,'<br>';echo '<h2>POST & PRE Decrement</h2>';echo 'The Value of $x-- = ',$x--,'<br>';echo 'The Value of $x = ',$x,'<br>';echo 'The Value of --$x = ',--$x,'<br>';echo 'The Value of $x = ',$x,'<br>';echo '<h1 align="center">Comparision Operator</h1>';
  • 70.
    70var_dump(10 == 10);echo'<br>';var_dump(10!= '10');echo'<br>';echo '<h1 align="center">Relational Operator</h1>';var_dump(10<=10);echo '<br>';var_dump(10<>'10');echo '<br>';//not Equal toecho '<h1 align="center">logical Operator</h1>';var_dump(true && true);echo '<br>';var_dump(true && false);echo '<br>';var_dump(true || true);echo '<br>';var_dump(true || false);echo '<br>';var_dump(false AND FALSE);echo '<br>';var_dump(false OR FALSE);echo '<br>';echo '<h1 align="center">Error Handling Operator</h1>';echo @sqrt();//@test();echo 'Some Data';echo '<h1 align="center">Scope Resolution & this Operator {:: & ->(this)}</h1>';class A{static $z = 100;public $a = 20;public $k = 50;
  • 71.
    71protected $b =30;private $c = 40;function test(){echo "A Test Function called inside Class A";}}$obj = new A;echo $obj->a,'<br>';echo $obj->k,'<br>';//echo $obj->b,'<br>';//echo $obj->c,'<br>';echo ' The Static Value is : ',A::$z,'<br>';echo 'The Function inside Class is : ',$obj->test(),'<br>';?>Type Casting: -Conversion of the one data type into another data type is known astype casting. in php we have mainly two types of costing1. Temporary type casting2. Permanent type casting1. Temporary type casting : Casting which can be done for singlestep by pre-defined the data type keyword. That particular variablewill hold Temporary type casting.
  • 72.
    72Ex : temporary.php<?php$x= "10.254Kgs";var_dump($x);echo "<br>";var_dump((int)$x); echo "<br>";var_dump($x); echo '<br>';var_dump((float)$x); echo '<br>';var_dump((boolean)$x);echo'<br>';var_dump((string)$x);echo "<br>";var_dump($x);echo "<br>";var_dump(floatval($x)); echo '<br>';var_dump(intval($x)); echo '<br>';var_dump($x);echo "<br>";?>2. Permanent type casting : This can be done by using pre-definedkey-word set type.which hold two argumentsSyntax : set type (var name,’int’);Ex : Permanent type casting.php<?phpecho '<h1>Permanent Type Casting</h1>';$x = "10.254Kgs";
  • 73.
    73settype($x,'float');var_dump($x);echo "<br>";settype($x,'int');var_dump($x);echo "<br>";settype($x,'boolean');var_dump($x);echo"<br>";settype($x,'int');var_dump($x);echo "<br>";var_dump($x);echo "<br>";settype($x,'float');var_dump($x);echo "<br>";?>Type juggling : conversion of data types by using expression toanother data types are known as type juggling.Ex : typejuggling.php<?phpecho 'true + true : ',true+true,'<br>';if(null){echo "Printed";} else {echo "Not Printed";
  • 74.
    74}?>Variable validation function:i) Isset : Isset of variables will check with the variable initialize ornot and return Booleanii) empty(var name) : empty function will check the variablewhether it is null or not and return Booleaniii) Unset (var name) : This function will remove the variable (or)delete the variableiv) get type(var name) : This function will let us know the argumentdata type in the form of string ,this should be used because thecoming variable would be depreciated.Ex : variable_validation.php<?php$x = 10;var_dump($x);echo '<br>';var_dump(isset($x));var_dump(isset($a));echo '<hr>';$z = '';var_dump(empty($z));var_dump(empty($y));$k = 10;echo '<br>';var_dump(gettype($k));
  • 75.
    75unset($x);var_dump(isset($x));?>Data Types :Phpsupports mainly 8 kinds of data types among which four arestable data types, two are compound data types and another two arespecial data typesa)Stable data types :i) int (or) integerii) Float (or) real (or) decimaliii) Boolean data typesiv) string data typesi)int (or) integer : All non decimal values . range in between 2(32-1)to -2(32-1)Ex :<?phpecho "<h1 align='center'>Stable Data types</h1>";echo "<h2>Integer Data Type</h2>";$x = 10;var_dump($x);echo '<br>';$x = (pow(2,32-1)-1);var_dump($x); echo '<br>';
  • 76.
    76$judge = 2147483647;var_dump($judge);?>ii)Float (or) real (or) decimal : All decimal values. Range inbetween 10(38) to 10(-38)Ex :<?phpecho "<h2>Float Data Type</h2>";$a = 10.25;var_dump($a);echo '<br>';?>iii) Boolean data types : Boolean data types return the values in theform of true (or) falseEx :<?phpecho "<h2>Boolean Data Type</h2>";$a = false;var_dump($a);?>iv) String data types : Collection of characters enclose in betweensingle (or) double cotations are known as string data types.
  • 77.
    77Ex :<?phpecho "<h2>StringData Type</h2>";$x = 10;echo '<br>The Value of $x is ',$x,'<br>';echo "The Value of $x is :$x";$name = "Rajesh";echo '<br>my name is $name <br>';echo "my name is $name <br>";$x = 10;$y = 20;echo 'The value of $x+$y = ',$x+$y,'<br>';echo "The value of $x+$y = ",$x+$y,'<br>';?>b)Compound data types :Compound data types again two types1. Array data type2. Object data type1. Array data type : Array data type which can hold more than onevalue. In php we have mainly 3 kinds of arraysi) Numerical arrayii) Associative array
  • 78.
    78iii) Mixed arrayDeclaringan array in php can be done by two types array as the function array as a square bracketi) Numerical array :A numeric array stores each array element with a numeric index.There are two methods to create a numeric array. In the following example the index are automatically assigned(the index starts at 0):$cars=array("Saab","Volvo","BMW","Toyota"); In the following example we assign the index manually:$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota";Ex :<?php$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota";echo $cars[0] . " and " . $cars[1] . " are Swedish cars.";?>ii) Associative array :An associative array, each ID key is associated with a value.
  • 79.
    79When storing dataabout specific named values, a numerical array isnot always the best way to do it.With associative arrays we can use the values as keys and assignvalues to them.Example 1In this example we use an array to assign ages to the differentpersons:$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);Example 2This example is the same as example 1, but shows a different way ofcreating the array:$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";The ID keys can be used in a script:<?php$ages['Peter'] = "32";$ages['Quagmire'] = "30";$ages['Joe'] = "34";echo "Peter is " . $ages['Peter'] . " years old.";?>The code above will output:Peter is 32 years old.iii) Mixed array :Mixed array is nothing but combination of numerical & associativearray is known as mixed array.
  • 80.
    80Ex : mixedarrays.php<?php$a= array("Name"=>"Rajesh","Age"=>30);print_r($a);echo '<hr>';echo '<h1 align="center">Mixed Arrays</h1>';define('A','ABC');define('B','XYZ');$c = 10;$d = 20;$g =array(0=>10,1=>20,'Name'=>'Raj','Age'=>30,5=>500,5.55=>600,-9=>'Negative value',true=>200,false=>200,''=>'EmptyValue',NULL=>'Null Value',A=>B,$c=>$d);echo '<pre>';print_r($g);echo '</pre>';?>2. Object data type :Object is an instance of class.Class can be denoted with in class name.Collection of variables and functions are known as class.For Callingclass we should create an object then that particular variable isknown as object variable.
  • 81.
    81Ex :<?phpecho "<h2>ObjectData Type</h2>";class A{public $x = 10;public $a = 20;function test(){echo 'A test Function called<br>';}}$b = new A;var_dump($b);echo '<br>Public Value $x = ',$b->x,$b->test(),'<br>';?>Special data types :Special data types are again two typesi) Resource data typesii) Null data typesi) Resource data types : Resource data type is calling an externalvariable value into another variable using (&) resource variable.
  • 82.
    82ii) Null datatypes : This is the pre-defined key-word. When avariable not initialize and by asking through printing method. Thiswill result in null value.Ex :<?phpecho "<h1 align='center'>Special Data types</h1>";echo "<h2>Reference Data Type</h2>";$x = 10;$y = $x;echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<br>';$x = 12;echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<br>';$y = 'Rajesh';echo 'The Value of $x = ',$x,'<br>The Value of $y = ',$y,'<hr>';echo "<h2>Resourse Data Type</h2>";$a = 10;$b = &$a;echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';$a = 'Raj';echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';$b = 'Amith';echo 'The Value of $a = ',$a,'<br>The Value of $b = ',$b,'<br>';
  • 83.
    83echo "<h2>Null DataType</h2>";var_dump($z);?>Constant :Define : Define is the pre-defined key-word in php. This will taketwo arguments. The first argument being the constant identifier whichidentifier its second argument value. We can pass third argument asBoolean to make case in-sensitiveEx : constant.php<?phpdefine('x',10,true);echo x,'<br>';echo X;echo '<hr>';define('url','http://www.socialhub.com',true);echo uRl,'/register.php';echo '<hr>';define('SITE_NAME','http://www.socialhub.in-hyderabad','SocialHub');?><h1>About us</h1>we at <?php echo SITE_NAME;?> are in training ........<h1>Contact Us</h1>
  • 84.
    84<?php echo SITE_NAME;?>street......<h1>FAQ</h1>what we do at <?php echo SITE_NAME;?>Conditions :Conditional statements are used to perform different actions based ondifferent conditionsa)If condition :IN PHPIN PERLIf (cond)if (cond) :{//code//codeelse if (code) :}//codeelse if (cond)else (cond) :{//code//codeend else if ;}
  • 85.
    85else (cond){//code}b)Switch condition:Syntax :switch (cond) :switch (cond):{|Case1 :|//code|Break;|Case2://code|Break;end switch;||Default://code}
  • 86.
    86Ex :<html><body><?php$x=1;switch ($x){case1:echo "Number 1";break;case 2:echo "Number 2";break;case 3:echo "Number 3";break;default:echo "No number between 1 and 3";}?></body></html>c)While condition : The while loop executes a block of code while acondition is trueSyntax:While (cond)while (cond):{//code inc/dec//const code inc/decendwhile}
  • 87.
    87Ex:<html><body><?php$i=1;while($i<=5){echo "The numberis " . $i . "<br />";$i++;}?></body></html>d)Do-while condition : The do-while statement will always executethe block of code once, it will then check the condition, and repeat theloop while the condition is true.Syntax :Do do:{ //codeInc/dec//code enddowhile(cond);}While (cond)Example :The example below defines a loop that starts with i=1. It will thenincrement i with 1, and write some output. Then the condition ischecked, and the loop will continue to run as long as i is less than, orequal to 5:<html><body>
  • 88.
    88<?php$i=1;do{$i++;echo "The numberis " . $i . "<br />";}while ($i<=5);?></body></html>e)For loop : Loops execute a block of code a specified number oftimes, or while a specified condition is true. The for loop is used whenyou know in advance how many times the script should run.Syntax :For(initialize;cond;inc/dec)//codeend forExample :The example below defines a loop that starts with i=1. The loop willcontinue to run as long as i is less than, or equal to 5. i will increaseby 1 each time the loop runs:<html><body><?phpfor ($i=1; $i<=5; $i++){echo "The number is " . $i . "<br />";}?></body></html>
  • 89.
    89f)for each :for each is usefull for all non-sequence data of an array.Associative array ,numerical array object data of an array.The general syntax isforeach (arrayName as arr[value])){echo arr [value];}Another syntax isforeach (arrayname as key=>value){echo key’-‘value (or) echo “key-value”;}Ex : foreach.php<?php$a = array("Name"=>"Rajesh","Age"=>30);/*foreach(arrayname as value){echo arr[value];}*/foreach($a as $v){echo $v,'<br>';}echo '<hr>';/*foreach(arrayname as key=>value){echo key,' - ',value;}*/foreach($a as $k=>$v){
  • 90.
    90echo "$k -$v<br>";//echo $k,' - ',$v,'<br>';}?>Functions :Functions are case in-sensitive.Once function can be declare con’t bere-declare in the program.The real power of PHP comes from its functions.In PHP, there are more than 700 built-in functions.To keep the script from being executed when the page loads, you canput it into a function.A function will be executed by a call to the function.You may call a function from anywhere within a page. Give the function a name that reflects what the function does The function name can start with a letter or underscore (not anumber)Syntax:function function name (arg){//codeReturn value}There are mainly 8 kinds of functions in php
  • 91.
    911. Conditional Function: A function which is enclose insidecondition is considered as conditional functionEx : conditional.php<?phpif(false){function test(){echo "I am a Conditional Function <br>";}}@test();2. Variable Function : When a function name is told In variable.Variable can be used for excuting the function in a place of functionnameEx : variables.php?phpfunction test(){echo "I am a Variable Function <br>";}test();$a = 'test';echo $a;echo '<br>';$a();$a();3. Function Function : Function is define inside another function iscalled as function-function.
  • 92.
    92Ex : function'sfunction.php<?phpFunction parent f(){echo “iam write the function function<br>”;If(!function_exists(childF)){function child F(){echo “I need some one to open parent file for me to excute<br>”;}}}Parent F();Child F();Parent F()’?>4. Function with arguments : Function can be defined with one (or)more arguments. If arguments are not passed then it creates warningin the programEx :<?phpfunction test($x,$y){echo 'The Value of $x = ',$x,'<br>';echo 'The Value of $y = ',$y,'<br>';}
  • 93.
    93test('Raj','Kiran');test(10,20);test('Amith');test();?>5. default argument: A function at the time of a declaration ifargument are assign with some values they will be treated as optional(or) default argument value and they can be passed with value (or)can left without passing the value. Works at the side default argumentmust be passing last in the program at the argument listEx :<?phpfunction test($x=10,$y=20){echo 'The Value of $x = ',$x,'<br>';echo 'The Value of $y = ',$y,'<br>';}test(100,200);test('Raj','Kiran');test();?>6. Overloaded argument : A function can be define with argument(or) that the defined arguments they are still acknowledge inside thefunction using various pre-defined functioni) func_num_args() : return the total number of arguments which arepassed in the function
  • 94.
    94ii) func_get_args() :return the array with all the arguments with thefunctioniii) func_get_args(position) : return the argument value at thespecified positionEx :<?phpfunction test(){echo "<h1>Overloaded Concept</h1>";echo 'The Overloaded Length = ',func_num_args(),'<br>';print_r(func_get_args());echo '<hr>';for($i=0;$i<func_num_args();$i++){echo 'Index at : ',$i,' - ',func_get_arg($i),'<br>';}echo '<hr><h1>For Each Method</h1>';$y = func_get_args();foreach($y as $k=>$v){echo "$k => $v<br>";}}test(10,20,'Rajesh');7. Function with Return value : Return key-word can be stop theexecution of the function.Return key-word can optionally followedwith a value which is return variable.Whenever a function is validanother one value con’t be passed after the return statement multiplevalue con’t be club as array (or) object and con’t be return wherever afunction is called.
  • 95.
    95Ex :<?phpfunction test(){echo"This is Return Information<br>";//return 10;echo "I am second info<br>";return = 82;echo "I am second info<br>";}test();$y = test();echo $y;//echo $y;8. i) arguments passed by value : When an argument passed byvalue any change for the value inside the function owned be reflectedin the variable outside the functionii) Arguments passed by reference : When an argument passed byresource and change for the inside with be refer to the variable outsidethe functionEx :<?phpfunction test($x,&$y){$x +=2;$y +=10; // $y = $y+10;echo 'The Value of $x = ',$x,'<br>';
  • 96.
    96echo 'The Valueof $y = ',$y,'<br>';}$a = 5;$b = 10;echo '$a = ',$a,'<br>';//5echo '$b = ',$b,'<br>';//10test($a,$b);echo '$a = ',$a,'<br>';//5echo '$b = ',$b,'<br>';//10?>Built-in Functions :a)Math Functions :Ex :<?phpecho 'Math Pi Value = ',M_PI,'<br>';echo 'Math Pi Value = ',M_PI_2,'<br>';echo 'Math Pi Value = ',M_PI_4,'<br>';echo 'Eulers Constant = ',M_E,'<br>';echo 'SQRT 2 = ',M_SQRT2,'<br>';echo 'SQRT 2 = ',M_SQRT1_2,'<br>';echo 'Log of 2 = ',log(2),'<br>';echo 'Log base 10 of 2 = ',log10(2),'<br>';echo 'Absolute Value = ',abs(-9),'<br>';echo 'Exponent of 1 = ',exp(2),'<br>';
  • 97.
    97echo 'pi() =',pi(),'<br>';echo 'ceil value = ',ceil(2.1111),'<br>';echo 'Floor Value = ',floor(2.9999),'<br>';echo 'round = ',round(2.51458),'<br>';echo 'round = ',round(2.51558,2),'<br>';echo 'rad2deg(M_PI) = ',rad2deg(M_PI),'<br>';echo 'rad2deg(M_PI) = ',rad2deg(M_PI_2),'<br>';echo 'rad2deg(M_PI) = ',rad2deg(M_PI_4),'<br>';echo 'deg2rad = ',deg2rad(180),'<br>';echo 'sin 90 = ',sin(M_PI_2),'<br>';echo 'tan 45 = ',tan(M_PI_4),'<br>';echo 'hypot value = ',hypot(3,4),'<br>';echo 'rand(min,max) = ',rand(100,1000),'<br>';echo 'min value = ',min(10,20,30),'<br>';echo 'max Value = ',max(2.999,2.998),'<br>';?>b)Date & Time Functions :Date : date is the pre-defined constant in php. It will generate currentdate according to the number of arguments passed.Mktime : Which can have arguments (hr, min, sec, month, day, year)unique time stamp.Check date() : Let us known the validate in a yearj----> represents day of the month without leading zerosl---->view letter represents of the day of the wayL---> whether it’s a leap year (or) not
  • 98.
    98W---> week numberof year weeks starts from Mondayw----> numerical represents of day of the way 0 for Monday through6 for SaturdayS---> English original safix for the day of the month two character ex:-st ,nd, rd,thF----> a full representation of the month such as January (or) MarchM---> short representation of the month such as jan (or) marm---> numerical representation of the month with leading zero’smeans 0-12n---> numerical representation of month without zero’s which is 1-12d---> number of days given in a month 28 (or) 31y---> two digits representation of a yearY---> it is representation of the full yearTime : Number of milliseconds sec right from unique time stampa---> lowercase ante meridiem and post meridiemA---> uppercase ante meridiem and post meridiemB---> swatch internet timeg---> 12- hours format of an hour without leading zerosG---> 24- hour format of an hour without leading zerosh---> 12- hours format of an hour with leading zerosH--->24- hours format of an hour with leading zerosi---> minutes with leading zero’ss---> seconds with leading zero’su---> microseconds (added in php 5.2.2)
  • 99.
    99Ex :<?phpecho 'Timezone set to : ',@date_default_timezone_get(),'<br>';date_default_timezone_set('America/Denver');echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';echo 'Today Date : ',@date("M-dS-Y, h:i:s a"),'<br><hr>';date_default_timezone_set('America/Los_Angeles');echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';echo 'Today Date : ',@date("M-dS-Y, h:i:s a"),'<br><hr>';date_default_timezone_set('Asia/Calcutta');echo 'Time zone set to : ',@date_default_timezone_get(),'<br>';echo 'Today Date : ',@date("M-dS-Y, h:i:s A"),'<br><hr>';var_dump(checkdate(02,29,1975));echo '<hr>No of milliseconds from Unix time Constant ',time(),'<br>';echo '<hr>Feature Date & time <br>';echo 'Event is on : ',(date("M-dS-Y, h:i:sa",mktime(7,9,52,8,23,2012))),'<br><hr>';echo date('Y');?>c)Array built-in Functions :<?php$a = array(10,20,30);function r($arr,$func=''){if(!empty($func)){
  • 100.
    100echo "<h2 align='center'><u>$func</u></h2>";}foreach($arras $k=>$v){echo "$k = $v<br>";}echo '<hr>';}echo 'Array count = ',count($a),'<br>';echo 'Size of = ',sizeof($a),'<br>';echo 'Sum of Array = ',array_sum($a),'<br>';echo 'Product of Array = ',array_product($a),'<br>';$a =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');r($a,'Normal Array');$b = array_change_key_case($a,CASE_UPPER);r($b,'Upper Case');$b = array_change_key_case($a,CASE_LOWER);r($b,'Lower Case');$b = array_flip($a);r($b,'Array Flip');$b = array_change_key_case(array_flip($a),CASE_UPPER);r($b,'Array Flip Values');$a = array('Doctor','Fruit','Software');$b = array('Patient','Orange','PHP');
  • 101.
    101r(array_combine($a,$b),'Array Combine');$a =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');echo'<h2 align="center">Array Chunk</h2>';$b = array_chunk($a,3);echo '<pre>';print_r($b);echo '</pre>';$a = array(10,20,30);$b = array(10,20,40,50);r(array_merge($a,$b),'Array Merge');r(array_intersect($a,$b),'Array Intersect');r(array_diff($a,$b),'Array Diff');$a =array('raj@gmail.com','amith@gmail.com','rohan@gmail.com','sumit@gmail.com','raj@gmail.com');r(array_unique($a),'Array Unique');r(array_reverse($a),'Array Reverse');$a = array(10,20,30);array_unshift($a,5);r($a,'Unshift Method');array_shift($a);r($a,'shift Method');array_push($a,40);r($a,'Push Method');
  • 102.
    102array_pop($a);r($a,'Pop Method');$ns =$ss = $as = $ks =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');r($ns,'Normal Array');sort($ss);r($ss,'Sorted Array');rsort($ss);r($ss,'Reverse Sort Array');asort($as);r($as,'Associative Sort Array');arsort($as);r($as,'Associative Reverse Sort Array');ksort($ks);r($ks,'Key Sort Method');krsort($ks);r($ks,'Key Sort Reverse Method');echo "<h2 align='center'>array_key_exists , array_search ,in_array</h2>";$a =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');echo 'Do i have Email Feild :',var_dump(array_key_exists('Gender',$a)),'<br>';echo 'Do we have Value with some :',var_dump(array_search(30,$a)),'<br>';
  • 103.
    103echo 'Do wehave Value with some :',var_dump(in_array('Male',$a)),'<br>';$a =array('Name'=>'Rajesh','Age'=>30,'Status'=>'Active','Email'=>'Raj@gmail.com','Gender'=>'Male');r(array_keys($a),'Array Keys Calling');r(array_values($a),'Array Value Calling');$str = 'Hey i am from India & my name is Praveen';$b = explode(" ",$str);//print_r($b);echo '<br>';echo 'The Length of your total Words = ',count($b),'<br><hr>';for($i=0;$i<count($b);$i++){echo 'The index at ',$i,' = ',$b[$i],'<br>';}$a =array('raj@gmail.com','amith@gmail.com','raju@gmail.com','suresh@gmail.com','raj@gmail.com','amith@gmail.com','raju@gmail.com','suresh@gmail.com');print_r($a);$b = implode(',',$a);<br><br>To : <input type='text' name='name' value='<?php echo $b;?>'size='60'/><hr><?php$a = array('born','child','teen','father','dead');r($a,'Normal Array');
  • 104.
    104echo 'The PresentPointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'Next : ',next($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'Previous location : ',prev($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'End Value : ',end($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<br>';echo 'Reset ',reset($a),'<br>';echo 'The Present Pointer is at : ',current($a),'<br>And the Key is at',key($a),'<hr>';$a = array('Name'=>'Rajesh','Age'=>30);r(Each($a),'Each Method');r(Each($a),'Each Method');$a = array('ram','processor','computer');list($gb,$intel,$dell) = $a;echo "$gb & $intel together makes $dell faster<br><hr>";$str = "write some large text matter.";echo $str,'<br><hr>';echo '<h2>Wordwrap</h2>';echo wordwrap($str,20,'<br>',true);?>
  • 105.
    105d)String built-in Functions:<?phpecho '<h2>';$str = "lamp institute";echo "Normal String = ",$str,'<br>';echo "Length of String = ",strlen($str),'<br>';echo "To Upper Case = ",strtoUpper($str),'<br>';echo "To Lower Case = ",strtoLower($str),'<br>';echo "Upper case First Word = ",ucfirst($str),'<br>';echo "Upper case words = ",ucwords($str),'<br>';echo 'Reverse = ',strrev($str),'<br>';echo '<hr>';echo 'Position of str = ',strpos($str,'t'),'<br>';echo 'last Position of str = ',strrpos($str,'t'),'<br>';echo 'Postion of str after t again = ',strpos($str,'t',9),'<br>';echo 'Position insensitive = ',stripos($str,'lamp'),'<br>';echo 'last position at t insensitive = ',strripos($str,'T'),'<br>';echo 'strstr will extract the entire string : ',strstr($str,"In"),'<br>';echo 'strstr will extract the entire string : ',stristr($str,"in"),'<br>';$name = 'Rajesh Kumar';echo "substr = ",substr($name,0),'<br>';echo "substr = ",substr($name,7,4),'<br>';echo "substr = ",substr($name,-5,-1),'<br>';$url = 'http://www.google.com?status=active';
  • 106.
    106$url .= '&';echo'substr = ',substr($url,0,-1),'<br>';echo 'replace = ',str_ireplace('lamp','Apache',$str),'<br>';$a ='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';echo str_shuffle($a),'<hr>';echo substr(str_shuffle($a),0,12);echo '<hr>';$name = "O'henry";echo $name,'<br>';echo addslashes($name),'<br>';echo stripslashes('O'henry'),'<br>';echo strip_tags("<b><i>Hi i am not feeling well</i></b>");echo '<hr>';echo '<h2>';$pwd = 'computer';echo 'Original Name : ',$pwd,'<br>';echo '<h1 align="center">One Way Encrypt</h1>';echo 'Encrypt with MD5 = ',md5($pwd),'<br>';//32 char valueecho 'Encrypt with MD5 strict = ',md5($pwd,true),'<br>';//16 bitbinary formatecho 'Encrypt with sha1 = ',sha1($pwd),'<br>';//40 char vlaueecho 'Encrypt with sha1 strict= ',sha1($pwd,true),'<br>';//20 binaryvlaueecho 'Crypt = ',crypt($pwd),'<br>';echo 'crypt salt = ',crypt($pwd,'d4'),'<br>';
  • 107.
    107echo '<h1 align="center">Encrypt& Decrypt Method</h1>';echo 'encrypt = ',base64_encode($pwd),'<br>';echo 'decrypt = ',base64_decode('Y29tcHV0ZXI='),'<br>';echo '<h1 align="center">Url Encode & Decode</h1>';$url = 'http://www.lamp.com?status=success&id=7&pid=20';echo 'Original url = ',$url,'<br>';echo 'encode = ',urlencode($url),'<br>';echo 'decode =',urldecode('http%3A%2F%2Fwww.lamp.com%3Fstatus%3Dsuccess%26id%3D7%26pid%3D20'),'<br><hr>';echo '<pre>';$name = " Rajesh ";echo 'My name is :',$name,'<br>';echo 'My name is :',rtrim($name),'<br>';echo 'My name is :',ltrim($name),'<br>';echo 'My name is :',trim($name),'<br>';echo '</pre>';?>PATH :FILE : The full path and filename of the file. If used inside aninclude, always contains an absolute path with some linksLINE : The current line number of the file.DIR : The directory of the file.Realpath : Returns absolute pathnameBasename : Returns filename component of path
  • 108.
    108Ex :<?phpecho "FileInformation : ",__FILE__,'<br>';echo "Base Name : ",basename(__FILE__),'<br>';echo "Directory Name : ",dirname(__FILE__),'<br>';echo "Directory Name : ",__dir__,'<br>';echo "real Path : ",realpath(__FILE__),'<br>';//echo "real Path : ",realpath('../..'),'<br>';echo "Line NO : ",__LINE__,'<br>';echo '<hr>';$a = pathinfo(__FILE__);//print_r($a);foreach($a as $k=>$v){echo $k,' = ',$v,'<br>';}?>e)File Functions :1) stat(file path) : This function Return an array with file information2)is_file(file path) : Checks wheather the file exist or not & ReturnsBoolean value.3)file_get_contents(file Path) : Returns the file content as a string.4)file_put_contents(fiel path,data) : Writes the content to the fileoverwriting old content and if file does not exists, creates a new file &adds the content.This function is introduced in 5th version.
  • 109.
    1095)file(file path) :Returns the file content as an array with each line inthe file at a particular index position.6)filectime(path) : Creates the time of the file.7)fileatime(file path) : Last access time of the path file.8)filemtime(file path) : Last modified time of the file.9)unlink(file path) : Removes the file from the location.10)filesize(file path) : Returns the size of the file in bites11)filetype(file Path) : Returns the type of the file (dir or file)12)fopen(file path,mode) : Opens the file in the specified mode andreturns a file handler for handling the file.13)fread(file handler, size) : Reads the file content from the currentfile handler position upto the specified size.14)$fp -> file Pointer ..The internal handler which is used forhandling the file.15)fgetc(file handler) : Reads a single char in the string.16)fgets(file handler) : Reads a single line from the file..17)fgetss(file handler) : Reads a single line from the file stripping ofhtml tags in the file.18)fwrite(file handler) : This function is used to write the content tothe file19)ftell(file handler) : Returns the file handler position in the file20)fseek(file handler) : Moves the file handler to the specifiedposition in the file21)fclose(file handler) : Closes the File handler connection.List of Modes :r --> Read Moder+ --> Read and Write.
  • 110.
    110w --> WriteModew+ --> Write & Read.a --> Append (also writing but without overwriting files)a+ --> append & read.x --> Creates a new file & write..x+ --> Creat a new file for write and read.rb,rb+,wb,wb+,ab,ab+,xb,xb+ are the modes to be used for binaryfiles.Examples for above specified actions :-----fileput.php<?php$file = 'a.txt';file_put_contents($file,str_repeat("MOd ",5));?>-----create.php<?php$file = 'c.txt';$fp = fopen($file,"x");fwrite($fp," Created");fclose($fp);if(is_file($file)){echo file_get_contents($file);}?>
  • 111.
    111-----write.php<?php$file = 'b.txt';$fp= fopen($file,"w");fwrite($fp,"Modified");fclose($fp);if(is_file($file)){echo file_get_contents($file);}?>-----read.php<?php$file = 'test.txt';$fp = fopen($file,"r");echo "Pos : ",ftell($fp),'<br>';echo fread($fp,3),'<br>';echo "Pos : ",ftell($fp),'<br>';echo fgetc($fp),'<br>';echo "Pos : ",ftell($fp),'<br>';echo fgets($fp),'<br>';echo fgets($fp),'<br>';echo 'Pos : ',ftell($fp),'<Br>';echo fgets($fp),'<br>';fseek($fp,35);
  • 112.
    112echo fgetss($fp),'<br>';fclose($fp);?>-----func.php<?php$file ='test.txt';var_dump(is_file($file));echo '<br>';echo "size : ",filesize($file),'<br>';echo "Type : ",filetype($file),'<br>';echo "Created : ",date("d-m-y h:i:s",filectime($file)),'<br>';echo "Accessed : ",date("d-m-y h:i:s",fileatime($file)),'<br>';echo "Modified : ",date("d-m-y h:i:s",filemtime($file)),'<br>';echo file_get_contents($file),'<br>';echo "<pre>";print_r(file($file));echo '<br>';print_r(stat($file));?>-----append.php<?php$file = 'b.txt';$fp = fopen($file,"a");fwrite($fp,"Append");
  • 113.
    113fclose($fp);if(is_file($file)){echo file_get_contents($file);}?>-----unlink.php<?php$file ='a.txt';unlink($file);?>f)Directory Functions:1)getcwd() : Current working directory,2)chdir(path) : Change current working dir to argumented path.3)is_dir(path) : Checks wheather the argumented dir exist or not andreturn Boolean value.4)mkdir(dirname) : Makes a directory on the current workinglocation.5)rename(old name,new name): Changes the name of the directory.6)rmdir(dir name) : Removes the directory.7)scandir(path) : Scan the directory and return the directory contentas an array. Returns an array with related path information.-----getcwd.php<?phpecho 'Cwd : ',getcwd(),'<br>';$a = scandir('.',0);
  • 114.
    114foreach($a as $k=>$v){echo"$k == $v<br>";}chdir('..');echo '<hr>';echo 'Cwd : ',getcwd(),'<br><hr>';$a = scandir('.',0);foreach($a as $k=>$v){echo "$k == $v<br>";}?>-----mkdir.php<?php$dir = 'test';if(!is_dir($dir)){mkdir($dir);echo "Directory is created";} else {echo "Directory already exists";}?>-----rename.php<?php$dir = 'test';$new = "modified";
  • 115.
    115if(is_dir($dir)){rename($dir,$new);echo "Directory nameis $new";}else {echo "Directory does not exists";}?>-----rmdir.php<?php$new = "modified";if(is_dir($new)){rmdir($new);echo "Directory is removed";}else {echo "Directory does not exists";}?>scandir.php<?phpecho '<pre>';var_dump(scandir('.'));?>
  • 116.
    116Super Globals :Differencebetween GET and POST :GET POST1.GET data transfers through URL. POST data is sendthrough request headers2.GET is insecure POST is secure3.File cannot be transfered using GET Files can betransfered4.Limited data can be send based on length We can send hugedata(8MB) which can be scaledof URL supported by browser(2KB). up by usingPOST_MAX_SIZE5.It is fast It is not as fast as GET.6.$_GET is used for accessing $_POST is used for accessingthe GET parameters the POST parametersGET Ex :-----get.php<?phpif(isset($_GET['submit'])){echo 'Name : ',$_GET['fname'],'<br>';echo 'Email Address : ',$_GET['email'],'<br>';$gend = ($_GET['gender'] == 'm')?'Male':'Female';echo 'Gender : ',$gend,'<br>';}
  • 117.
    117echo '<hr>';echo urldecode($_SERVER['QUERY_STRING']);echo'<hr><br>';?>-----get.html<form method='GET' action='get.php'>Name : <input type='text' name='fname' value=''><br>E-Mail : <input type='text' name='email' value=''><br>Gender : <input type='radio' name='gender' value='m'> Male <inputtype='radio' name='gender' value='f'> Female<br><input type='submit' name='submit' value='Register !'></form>POST Ex :-----post.php<?phpif(isset($_POST['submit'])){echo 'Name : ',$_POST['fname'],'<br>';echo 'Email Address : ',$_POST['email'],'<br>';$gend = ($_POST['gender']=='m')?'Male':'Female';echo 'Gender : ',$gend,'<br>';$a = $_POST['course'];echo $a,'<br><hr>';print_r($a);}echo '<hr>';echo 'The query string : ',$_SERVER['QUERY_STRING'],'<br>';
  • 118.
    118?>-----post.html<form method='POST' action='post.php'/>Name: <input type='text' name='fname' value=''/><br>E-Mail : <input type='text' name='email' value=''/><br>Gender : <input type='radio' name='gender' value='m'/> Male <inputtype='radio' name='gender' value='f'/> Female <br>Hobbies : <br><input type='checkbox' name='course[]' value='c'/> C-Language <br><input type='checkbox' name='course[]' value='p'/> PHP <br><input type='checkbox' name='course[]' value='j'/> Java <br><input type='submit' name='submit' value='Register'/></form>Server Variables :-----servervariables.php<?phpecho 'Get Environment : ',getenv('os'),'<br>';echo 'Environment Path : ',getenv('path'),'<br>';echo '<hr>';echo 'Document Root : ',$_SERVER['DOCUMENT_ROOT'],'<br>';echo 'Http Host : ',$_SERVER['HTTP_HOST'],'<br>';echo 'Referer : ',$_SERVER['HTTP_REFERER'],'<br>';echo 'Method : ',$_SERVER['REQUEST_METHOD'],'<br>';echo 'User Agent : ',($_SERVER['HTTP_USER_AGENT']),'<br>';
  • 119.
    119echo 'Name ofScript : ',$_SERVER['SCRIPT_NAME'],'<br>';echo 'Query String : ',$_SERVER['QUERY_STRING'],'<br>';echo 'Remote Ip Address : ',$_SERVER['REMOTE_ADDR'],'<br>';echo 'PHP Self : ',$_SERVER['PHP_SELF'],'<br>';echo 'Request URL : ',$_SERVER['REQUEST_URI'],'<br>';echo 'Script File Name : ',$_SERVER['SCRIPT_FILENAME'],'<br>';?>-----phpinfo.php<?phpecho phpinfo();?> Include_once and required _once : These both will include filevery first time and if already file has been included this will notinclude for the second time. Defference between include_once & include : Include andinclude _once will include the files. But if the path of the file is wronginclude and include_once will generate the wrong message and rest ofthe code will be excuted.Required and required_once : If location of the path is givenwrong this will through a wrong as well as path error and code getshalted or the execution will be stop.Ex : a.php<style>b{color:green;}</style><b>I am included</b><br><hr><?php
  • 120.
    120$a = 10;if(!function_exists('r')){functionr(){echo 'I am in a.php and working fine<br>';}}?>b.php<?phpinclude_once("a.php");include("a.php");include("a.php");$b = 20;echo 'The Value of $a = ',$a,'<br>';echo 'The Value of $b = ',$b,'<br>';r();?>Headers :Headers are the information which are exchanged between client andserver for every request and response.Headers are of two types.a) Request Headers.b) Response Headers.a) Request Headers : These are send from client to server.
  • 121.
    121HTTP Request :GET/php7/info.php HTTP/1.1Host : localhostUser_Agent : Mozilla/5.0Accept : text/HTML, application/htmlAccept_encoding: gzip,deflateConnection : keep-alivekeep-alive : 115Accept_char : ISO-88591-1 utf-8;q=0.7Ex : apache_request_headers()b) Response Headers : These are send from server to client.X-powered-by : php/5.3.1keep_Alive : timeout=5,max=100connection : Keep_AliveTransfer_Encoding : chuntedcontent_type : text/htmlEx : apache_response_headers()HTTP Methods :For every request from the client to server can be made throughvarious HTTP methods likeGET, POST, PUT, DELETE, HEADHeaders can be send from php program to the server.1. headers_list() : Returns an array to the list of the headers whichcan be shared from server to client.
  • 122.
    1222. headers_sent() :Returns the boolean value above whether theheaders were send to the client or not.3.header("<name>:<value>") : Header function should be used inthe page before any output is send to the page.Header functions are used for redirection and for sending the outputand also for downloading of the files.Php content in different formats(content type likehtml,xhtml,images,pdf,flash,video etc).Ex :-----hrds.php<?phpob_start();print_r(apache_request_headers()); echo '<hr>';var_dump(headers_sent());header("Name:Rajesh");header("location:info.php");print_r(headers_list());echo '<hr>';print_r(apache_response_headers());?>-----info.php<?phpecho phpinfo();?>
  • 123.
    123Downloading :Step 1:Download of a file is done by sending few headers followedwith reading of source file from the server sending a content typeheader.header("Content-Type:<mine Type>");pdf -> application/pdf.html -> text/html.jpg/png/gif -> image/(jpg || png || gif).Step 2: Sending a content Disposition header which will tells thebrowser to open the file or to ask the user about the file.header("Content-Disposition:<mode>;filename=<filename>");----->Inline----->attachmentStep 3: Optionally we can sent content length header with the size ofthe file.header("Content-Length:<filesize(finename)>");Reading the Original file :readfile(<path of file>)  Reads the file Content and prints to thebrowser.Ex : download.php<?php$file="01.jpg";$type="image/jpg";$mode="inline";header("Content-Type:".$type);header("Content-Disposition:".$mode.";filename=".$file);header("Content-Length:".filesize($file));
  • 124.
    124readfile($file);?>----down.phpmage down <ahref="download.php"/>View Please</a>File Uploading :upload_tmp_dir(<path>) : default is set to c:xampptmp. Thetemporary location to which the file can be uploaded to the server.upload_max_filesize : (<128>) The max size for a single file whichcan be uploaded to the server -> max_file_uploads : 20.Functions in upload :copy of source destination : Copy the file from source location todestination folderis_upload_file(source path): Checks wheather file upload or notand return boolean.move_upload_file (<source path, destination>): Moves the filefrom source location to destination locationPredefined variables: - $_FILES is predefined super global filewhich will be loaded with theProperties in file upload :1. $_FILES[<file_field_name>]['name']: It returns the originalname of the uploaded file.2. $_FILES[<file_field_name>]['tmp_name']: It returns thetemporary path to the uploaded file.(It acts as the source path of the uploaded file in the program).3. $_FILES[<file_field_name>]['size']: It returns the size of theuploaded file in bytes.4. $_FILES[<file_field_name>]['type']: It gives the MIME(Multipurpose Internet Main Extension) type for the uploaded file.
  • 125.
    1255. $_FILES[<file_field_name>]['error']: Itreturns the error codeassociated with the file upload.If its value is configured to zero indicates no error.Ex : testupload.php<?phpif(isset($_POST['submit'])){if(isset($_FILES['photo'])){$src = $_FILES['photo']['tmp_name'];$desc ="pics/".getRandString(12).$_FILES['photo']['name'];if(move_uploaded_file($src,$desc)){echo 'Image saved successfully<br>';} else {echo 'Image not saved<br>';}}}echo '<hr>';function getRandString($size){$a =str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');return addslashes(substr($a,0,$size));}?>
  • 126.
    126-----test.php<form action='testupload.php' method='POST'enctype='multipart/form-data'/>UploadPhoto : <input type='file' name='photo'/> <input type='submit'name='submit' value='Upload'/></form>COOKIES :Cookies are super global variables which can be stored at clientmachine.$_COOKIE: It is a predefined super global variable which can beused for reading cookie data.setcookie(<name>,<value>): It is a predefined function for creating,updating or deleting the cookie variable at server machine.cookie values are stored at the browser of client's machinecookies are not safe for storing the information.Every webbrowser is limited to a certain number of cookies to bestored at the client's machine(~20).Cookies information will be exchanged between the client and serverevery request and response through headers.If Cookie is once created can be accessed from the next request fromthe server to the client but not in the same page.setcookie(<name>,<value>,[<lifetime>],[<domain>],[<path>],[<secure protocol>])lifetime: Timestamp upto which cookie must be active.time()+24*60*60domain: news.abc.comgmail.com
  • 127.
    127path: Default pathis current working directory/  Points to root directory/abc  Cookie is shared with all files in abc foldersecure_protocol: If it is true then it will be exchanged with httpsprotocol otherwise with http protocolCookie can be created in two ways.1. By creating cookie with empty value.2. By creating the cookie in the pastEx : create.php<?phpob_start();print_r($_COOKIE);setcookie('c',10,time()+3600);//set cookieecho "<br>";print_r($_COOKIE);setcookie('c',88,time()+3600);//modify or updateecho "<br>";setcookie('c',"",time()+3600);//deleteecho "<br>";setcookie('c',"abc",time()-3600);//deleteecho "<br>";?>setcookie will sends a header to the server(No output is sent beforeusing.)If output is started before it use output buffering.
  • 128.
    128SESSIONS :It isused for maintaining the state of the user between his login andlogout. Session information is stored at the server machine and isaccessable with the pages where session is started.$_SESSION is a predefined super global used for managing sessiondata.Configuration Settings:session.auto_start(OFF) : Controls whether the session must beautomatically started or not.session.name=PHPSESSID: The default name at which session id isstored at a client machine as cookie variable.session.use_cookie(ON*/OFF): Using the cookies for storing thesession id value.session.use_only_cookies: Using cookies only for storing the sessionid.session.use_trans_sid(0/1): Using a transferable session id throughURL.session.gc_maxlifetime(1440(24minutes)): The maximum time forwhich the session data can be maintaines when the user is idle beforesending to gc(garbage collector).Functions in SESSIONS :session_start(): Starts a new session for the user, if session alreadyaxists uses the already existing session.session_name[<optional_name>]: Gets or sets the name of thesession.session_id(): It returns the session id created for the user. A sessionid is a unique 32 character length alphanumeric value.session_regenerate_id : Changes the session id to new one for theuser.
  • 129.
    129session_unset: Erases thesession data for the user.session_destroy: Session will be destroyed.Ex : session.php<?phpob_start();session_start();echo 'Session Name : ',session_name(),'<br>';echo 'Session Id : ',session_id(),'<br>';echo 'Session Name : ',session_name('Rajesh'),'<br>';echo 'Session Name : ',session_name(),'<br>';echo 'Session generate Id : ',session_regenerate_id(),'<br>';echo 'Generated Id : ',session_id(),'<br>';echo 'Life time : ',(ini_get('session.gc_maxlifetime')/60),' mins<br>';echo 'Session save Path : ',ini_get('session.save_path'),'<br>';echo 'Cookie Save Path : ',ini_get('session.cookie_path'),'<br>';$_SESSION['Name'] = 'Praveen';$_SESSION['Email'] = 'raj@gmail.com';print_r($_SESSION); echo '<hr>';print_r($_COOKIE);echo '<hr>';session_destroy();echo 'Session Id : ',session_id(),'<br>';print_r($_SESSION);unset($_SESSION['Name']);echo '<hr>';print_r($_SESSION);
  • 130.
    130echo '<hr>';print_r($_COOKIE);?>Global ConfigurationSettings :Understanding Configuration settings in PHP:1) POST_MAX_SIZE : Max size of post data that a php will accept2) magic_quotes_gpe : Escaping of " Quotations with a backslash forthe data which is sent through GET,POST,COOKIE & ENVvariables.Default value is set to ON.3) Register_globals : Possible values are ON and OFF. By default isOFF. Registering of super global variable as regular variables in thispage is controlled with this settings4) variables_order : "GPCS";The order which superglobal variableare loaded with the current working page5) Register_long_arrays : ON or OFFThe availability of superglobals array with login array names used inthe older version of PHP is controlled with this settings.6) file_uploads: ( ON) whether to allow HTTP Files to upload or not;Buffer :Buffering of the output before sending with browser can be handledby using output buffering.Configuration settings :Output_buffering = 4096Buffers the output upto 4KB and releases the output.Functions :ob_start() : Starts the buffering output if buffering is inactive.
  • 131.
    131ob_get_length : Itreturns the size of buffer content in the pageob_flush() : It sends the buffer content to the browser.ob_get_flush() : It returns the buffer content as a string and sends thebuffer to the browser.ob_clean() : It clears the buffer and stops the buffering.ob_get_clean : It cleans the buffer content and returns it as a string.Note : Output buffering is used when we are working with sessionsusing headers with in the page.Ex : buffer.php<?phpob_start();echo 'Line 01<br>';echo 'Line 02<br>';echo ob_flush(); //implicit_flush = Off;header("Name:Rajesh");//echo ob_get_length();echo '<hr>';echo ob_get_contents();?>
  • 132.
  • 133.
    133MySQLMySQL is aOpen Source database server which is developed on topof C & C++ Languages.MySQL supports many programming & Scripting languages forproviding access to the data like C,C++,Java,.Net,PHP,PERL,Pythonetc..MySQL was initially developed by MySQL-AB Group of sweaden,which was merge with Sun Microsoft system in Aug 8th, 2008..MySQL Supports ANS Based SQL FOR Communicating withdatabase server MySQL will allow the SQL statement to get executedthrough various channel like.1) GUI Tools(Graphic user Interface),MySQL Administrator,SQLyog, SQL etc2) Web Based Tools(phpmyadmin, SQL ETC...)3) Command Line Interface : Accessing local database Server Locally4) Data : This is collection of informationDatabase : It is a collection of DataDBMS :DBMS stands for Data Base Management System.It Suggests theinternal Organization in Database Server.DBMS is used for defining Structural architecture of data base andinternal organization of the data in Various types of DBMS.1)HDBMS (Hierarchical Data Base Management System)2)NDBMS (Network Data Base Management System)3)RDBMS (Relational Data Base Management System)4)ODBMS (Object Data Base Management System)
  • 134.
    1345)ORDBMS(Object Based RelationalData Base ManagementSystem)RDBMS :In RDBMS db is considered as a collection of tables, each table is acollection of records, and each record consists of collection of data set(cols,rows).E.F.CODD : 12 Rules of RDBMS..can be found at(http://www.cse.ohio-state.edu/~sgomori/570/coddsrules.html)Normalization :5 Forms(1st three has to understood);SQL : Structural Query Language which is used for Communicatingwith data base Server.Database Server : It is a Software which will receive the request inSQL and sends the data as the response.Eg: MySQL,Oracle,Sybase,Postgre SQL,DB2,MSSQL,MS AXISetc..SQL:a)DDL(Data Defination Language)CREATE -------------|---> Database|  Table||DROP ---------------|---> Database|  Table|ALTER---------------|--->Used for Tables
  • 135.
    135|  ADD| CHANGE|  DROPTRUNCATE------------|--->TABLEb)DML (Data Manipulation Language)|  INSERT INTO|  UPDATE SET|  DELETE FROMc)DRL (Data Retrivel Language)|  SELECT |  WHERE <cond>|  ORDERED BY <field-Name>|  GROUP BY <field-Name>|  LIMIT <start>,<end>d)DCL (Data Controlling Language)|  ADMIN ZONEe)TCL (Transaction Control Language)|  Giving Special Permission.Data Base LevelQuery :SHOW DATABASES  Return the List of DatabasesCREATE DATABASE  <db_name> Creates a database if it is notExisting.a)USE <db_name>  Select a database for executing further Queriesin the Table.b)DROP DATABASE<db_name>  Deletes the database from thedatabase server Completely with its Tables and data.
  • 136.
    136Table Level Query: SHOW TABLES[FROM <db_name>]; CREATE TABLE <table_name> (<field_name><datatype>[<size>] <add_parementers> <field_info); ALTER TABLE <table_name> ADD <field_info>; CHANGE <field_name> <new_field_info>;ALTER TABLE <table_name> DROP <field_name>;RENAME <new_name>;(Renaming a Table) TRUNCATE <table_name>;This will empty the table. Removes the complete data ofthe table but the structure of table remains same in the database. DROP<table_name>; Removes the table data and its Structure;Data Level Query :Data manupulation Language:INSERT INTO <tbl_name> [(<field_list>)] VALUES[(<value_list>),(<value_list2),(value_list3)...]; UPDATE <tbl_name> SET <field_name> = <new_value>WHERE <cond>; DELETE FROM <tbl_name> WHERE <cond>;Data Retrival Query: SELECT (* or <field_list>) FROM <tbl_name> [WHERE<cond>] ORDER BY <field_name> ASC/DESC [GROUP BY<field_name> LIMIT <start_index>[,<length>]];Numerical Datatypes in MYSQL :1) Tiny Int : [2pow8 -1] 0-255  UNSIGNED[-128-127] SIGNED
  • 137.
    1372) Small Int: 2 bytes [2pow16-1]  UNSIGNED-32767 TO -32767  SIGNED3) Mediun Int : 3 bytes [2pow24-1]UNSIGNED int [16777215]SIGNED int [-8388607]4) Int : 4 bytes [2pow31-1]SIGNED Int Range [2147483647]5) BigInt : 8 bytes [2pow64-1]0 - 1.84467440737096e+14 20digitsSize of integer will specify the total number of digitsAdditional Parameter SIGNED OR UNSIGNED default Value isSIGNED.6) float(<no of digits>,<precision>) :A small number with a floating Value .10POW38 0-24(falls in float)7) Double(no of digits>,<precision>) :A Large Number with a floating Decimal Point(25-5)8) Decimal() : A double stored as a string, allowing for a fixeddecimal point.9) Char() : A fixed Section from 0 to 255 character Long.10) varchar() : A variable section from 0-255 char long.Miscellaneous Types :ENUM() : ENUM stands for Enumeration, which means that eachcoloumn may have one of a specified possible Value.Text : String Content 65kb for this size is needed.medium text : 0 - 16777215 char (16mb) can be accomidated inmedium text..
  • 138.
    138long text :0 to upto 4gb long textENUM :ENUM is a Miscellaneous datatype . Enumeration field used forstoring Optional values among which one value can be selected whileinserting (0-65535) maximum number of optiona, which are allowedall string values must be enclosed in "Quotations" while inserting.Date Data types :Date : YYYY-MM-DD(0000-9999)allowed datesTime : hh:mm:ssDate & Time : YYY-MM-DD hh:mm:ssTIME STAMP : Defaultly insert the current date and time values.yyyymmdd hhmmss  14yyyymmdd hhmm  12yymmddhhmm  10yyyymmdd  8yymmdd  6Year : 4-digits Year number ,all date values must be enclosed inQuotations during the insertion.Binary Data Types :Binary : Fixed length binary content (similar to char)Var binary : it is variable length binary content similar to varchar.Blob : binary Large Object similar to text data typeMedium Blob : Similar to medium Text.Long Blob : similar to Long Text.
  • 139.
    139Additional Parameters :1)PRIMARY KEY : Atleast one field in a table must be declared asprimary key, it is UNIQUE it is by default an INDEX for the table. itcan't be NULL.2) FOREIGN KEY: The field which establish a relation to theprimary key field of the table is foreign Key.3) UNIQUE : The field apart from primary Key which needs to beUNIQUE can be applied with this field..4)CURRENT_TIMESTAMP : Predefined constant which can storecurrent time stamp value by default at the time of inserting the date ortime. On update current-time stamp it is used for adding current timestamp at the time of updation.5) AUTO_INCREMENT : Increase the value by one automaticallyfor every row record entry. CreateCREATE TABLE eg_user(Id SMALLINT(5) UNSIGNED NOTNULL PRIMARY KEY AUTO_INCREMENT, EmailIdVARCHAR(100) NOT NULL UNIQUE, Pword CHAR(32) NOTNULL, Gender ENUM('Male', 'Female') NOT NULL,DateOfBirthDATE NOT NULL,RegisteredOn TIMESTAMP DEFAULTCURRENT_TIMESTAMP, uStatus ENUM('Inactive', 'Active') NOTNULL);DESC eg_user;DESCRIBE eg_user;EXPLAIN eg_user; Inserting recordsINSERT INTO eg_user (EmailId, Pword, Gender, DateOfBirth)VALUES ('mra@xyz.com', MD5('abc'), 'Male', '12-12-1980');
  • 140.
    140 List allrecords of tableSELECT * FROM table_name;Inserting multiple recordsINSERT INTO eg_user (EmailId, Pword, DateOfBirth, Gender)VALUES ('mrb@xyz.com', MD5('1'), '1979-10-19','Male'),('msc@xyz.com',MD5('a'), '1980-5-12','Female'),('mrd@xyz.com',MD5('ab'), '1972-6-10','Male'),('mse@xyz.com',MD5('AB'), '1989-12-12','Female'); Modifying the recordUPDATE eg_user SET DateOfBirth='1980-12-8', uStatus='Active'WHERE Id=1;Deleting the recordDELETE FROM eg_user WHERE Id=5;TRUNCATE TABLE tbl_name;Example : Create emp tableCREATE TABLE eg_emp(Id SMALLINT(5) UNSIGNED PRIMARY KEYAUTO_INCREMENT,Name VARCHAR(30) NOT NULL,Salary DECIMAL(10,2) NOT NULL,Location VARCHAR(50) NOT NULL) AUTO_INCREMENT=101;Inserting RecordsINSERT INTO eg_emp (Name, Salary, Location) VALUES('Mr.A',5000, 'Hyd'),('Mr. B', 4500, 'Mumbai'), ('Ms. C', 6000,'Delhi'),('Mr. D', 7000, 'Delhi'),('Mr. B', 5000, 'Hyd'),('Ms. E', 3000, 'Hyd');
  • 141.
    141Read records foronly specified columns Name, locationSELECT Name, Location FROM eg_emp;List emps with salaries < 5000SELECT * FROM eg_emp WHERE Salary<5000;List emps whose salary is either 3000, 5000, 4000, 7000SELECT * FROM eg_emp WHERE Salary=3000 OR Salary=5000OR Salary=4000 OR Salary=7000;SELECT * FROM eg_emp WHERE SalaryIN(3000,5000,4000,7000);List emps whose salaries are between 5000 & 8000SELECT * FROM eg_emp WHERE Salary>=4500 ANDSalary<=8000;SELECT * FROM eg_emp WHERE Salary BETWEEN 5000 AND8000;List users born between 1-1-1970 and 31-12-1980SELECT EmailId, DateOfBirth, Gender FROM eg_user WHEREDateOfBirth BETWEEN '1970-1-1' AND '1980-12-31';SELECT CURRENT_DATE;SELECT CURRENT_TIME;SELECT MONTH(CURRENT_DATE)SELECT MONTHNAME(CURRENT_DATE);SELECT WEEKDAY(CURRENT_DATE)SELECT DAY(CURRENT_DATE)SELECT DAYNAME(CURRENT_DATE)SELECT EmailId, DateOfBirth FROM eg_user WHERE MONTH(DateOfBirth) = 12;SELECT COUNT(Id) FROM eg_user;
  • 142.
    142SELECT SUM(Salary) FROMeg_emp;SELECT SUM(Salary) FROM eg_empWHERE Location='Hyd';SELECT MAX(Salary) AS HighestSalary FROM eg_emp;SELECT MIN(Salary) LeastSalary FROM eg_emp; Number of emps for every locationSELECT COUNT(*) TotalEmps, Location FROM eg_empGROUP BY Location; Number of emps for every location with salary > 4000SELECT COUNT(*) TotalEmps, Location FROM eg_empWHERE Salary>4000GROUP BY Location; List of locations with 2 or more emps having salary>4000SELECT COUNT(*) TotalEmps, Location FROM eg_empWHERE Salary>4000GROUP BY LocationHAVING TotalEmps>1;Salary in descending orderSELECT * FROM eg_empORDER BY Salary DESC;//Salary in desc, with Id descSELECT * FROM eg_empORDER BY Salary DESC,Id DESC;
  • 143.
    143List second highestearnerSELECT * FROM eg_empORDER BY Salary DESCLIMIT 1,4; Create Another TableCREATE TABLE brand(Id TINYINT(2) UNSIGNED PRIMARYKEY AUTO_INCREMENT,BrandName VARCHAR(50) NOTNULL);INSERT INTO brand(BrandName) VALUES('Adidas'),('Nike'),('Nokia'),('Titan'),('Lg');CREATE TABLE category(Id TINYINT(2) UNSIGNED PRIMARYKEY AUTO_INCREMENT,Name VARCHAR(50) NOT NULL);INSERT INTO category(Name) VALUES('Mobiles'),('TShirts'),('Jeans'),('Watches'),('Electronics'),('books');CREATE TABLE products(Id SMALLINT(5) UNSIGNEDPRIMARY KEY AUTO_INCREMENT,Name VARCHAR(50) NOTNULL,Amount DECIMAL(10,2) NOT NULL,in_StockTIMESTAMP DEFAULT CURRENT_TIMESTAMP,c_idTINYINT(2) UNSIGNED NOT NULL,b_id TINYINT(2)UNSIGNED NOT NULL);INSERT INTO products(Name,Amount,c_id,b_id) VALUES('Smart watch',612.954,4,4);SELECT * FROM products,category;SELECT p.Name,p.Amount,c.Name FROM products p,category c;SELECT p.Name Products,p.Amount,p.in_Stock,c.Name CategoryFROM products p,category c WHERE p.c_id = c.Id;SELECT p.Name Products,p.Amount,p.in_Stock,c.NameCategory,b.BrandName FROM products p,category c,brand b
  • 144.
    144WHERE p.c_id =c.Id AND p.b_id = b.Id ORDER BY AmountDESC;PHP by Default Support With Mysql library,,PHP communication with Mysql can be Splitted int some steps like1) Connecting to the Database2) Selecting to the Database3) Query the Database4) Fetching the Records or Getting the records From Query or QueryString.5) Close the Connection.1) Connecting to the Database Among them We haveA) Normal Connection B) Persistance ConnectionNormal Connection : Will be active for the Single Program, ANormal Connection can be Closed by Using mysql_close();mysql_connect('hostname','username','password');B) Persistance Connection : A Persistance Connection is aPermanent Connection Once establish it cannot be closed.mysql_pconnect('hostname','username','password');2) Selecting to the Databasemysql_select_db('dbname',[Optional Conn Handler]);Selects the Argumented data as current data...Error Handling in Database :a)mysql_error() : Returns the last Error Message Occured with thedata base server.
  • 145.
    145b)mysql_errno() : Returnsthe last error code associated with themysql database Server.3) Querying the Database :a) mysql_query(SQL) : Executes the Query with the database serverand returns the Query Handler.b) mysql_affected_rows : Returns the number of rows affected forthe last insert, Update or delete Query.c) mysql_num_rows(Query handler) : Returns the number ofrecords in the resultant for the select Query .4) Fetching the Records :a) mysql_fetch_row(Query handler) : Returns a single record setfrom the database server, as a numerical array and moves the queryhandler to next record if record does not exist return false.b) mysql_fetch_assoc(Query handler) : Returns the record Set as anassociative array with field names as its index position - if record doesnot exist return false..c) mysql_fetch_array(Query handler) : Returns the record set as anarray with numerical or associative or both arrays . Returns false if norecord found.d) mysql_fetch_object(Query handler) : Returns the record set asan object with field names as its values .5) Close the Connection :a)mysql_close : Close the connection with the data base.There are 2 other functions in php.Which gives a message.if not able to connect to database then we can read the message asdie('Message');die(mysql_errno().' - '.mysql_error()); or exit;
  • 146.
  • 147.
    147OOPSClass :It isa collection of properties (variables) and methods.Syntax :class <class_name>{//code}[abstract|final] class <class_name>{//code}Property (or) member : A property or member of a class is anidentifier which is used for storing data which can be accessiblethroughout the class.<public|protected| private>[static] <var> =<value>;Ex :public $x=10;protected $account_no=null;static public $conv_rate=0.87;Method :A method is an action for a class (or) a method is a function inside theclass
  • 148.
    148Syntax :[static][final|abstract][public*|protected|private] function<fun_name>([args]){//code}Ex:function getName(){return $this->name;}Object :It is an instance of a class.Object is used for accessing classproperties(public). Object can execute methods(public).Syntax :<object>=new <class_name>[args];It is the operator which is used for accessing class propertiesand excuting class methods using an objectEx :<?phpclass A{public $x=20;public function test(){
  • 149.
    149echo "Test function<br>";}}$obj=newA;var_dump($obj);echo '$obj->x=',$obj->x,'<br>';$obj->test();$obj->x=21;echo '$obj->x=',$obj->x,'<br>';$obj2=new A;echo '$obj2->x=',$obj2->x,'<br>';?>Constructor :It is a predefined method which is automatically executed within theclass when a class is instantiated. Any argument must be passed tothe class at the time of instatiation.constructor() : It is the predefined name which can be used for theconstructor in a class(php>=5.0). For PHP<5.0 version constructorname must be similar to class name.Ex :<?phpclass Human{public $name="ram";public $age=0;
  • 150.
    150function getName(){return $this->name;}functiongetAge(){return $this->age;}function setName($n){$this->name=$n;}?>$this is a predefined variable which will be instantiated in a classwhen an object is called.$surya=new Human;$surya->name='suryaprakash';$surya->age=32;$juli=new Human;$juli->name='julia robert';$juli->age=45;Destructor (>=PHP 5.0) :The method which will be automatically called when the class objectis uninitialised in the program.destructor() : It is the prereserved name for the destructor.Class constant :const <name>=<value>;
  • 151.
    151Ex :const X=10;Classconstants are case sensitive. They are suggested to begin withuppercase.Class constants are specific in class, they must be uniquewith in the class.:: (Scope Resolution Operator):It is used for accessing static properties,class constants and Executingstatic methods.Accessing the class constant :Syntax :<class_name>::<constant_name>Self : self is a predefined keyword used for refering the same classwithin the class in scope resolution operator convertion.Parent : parent keyword refers to the parent class.Ex : -<?phpclass Person {private $name;public function __construct($name) {$this->name = $name;}public function getName() {return $this->name;}public function getTitle() {
  • 152.
    152return $this->getName()." theperson";}public function sayHello() {echo "Hello, I'm ".$this->getTitle()."<br/>";}public function sayGoodbye() {echo "Goodbye from ".self::getTitle()."<br/>";}}class Geek extends Person {public function __construct($name) {parent::__construct($name);}public function getTitle() {return $this->getName()." the geek";}}$geekObj = new Geek("Ludwig");$geekObj->sayHello();$geekObj->sayGoodbye();?>Inheritance :It inherites the properties and methods of a base class to an extendedclass is known as inheritance.
  • 153.
    153Base class :A class from which properties and methods are inheritedto child class.Base class can be called as parent class or super class.Extended class or child class or sub class : The class which inheritsthe properties and methods from a base is known as an extended classor child class or sub class.Note : PHP supports multi-level inheritance but won't supportmultiple inheritance.Multilevel inheritance :class A{}class B extends A{}class c extends b{}Multiple inheritances :class X extends Y,Z,W{}//wrongExtends: A predefined key word which is used for inheriting a class.Ex: -class A{public $x=20;
  • 154.
    154function test(){echo "testmethod<br>";}}class B extends a{}$b=new B;echo $b->test();Overriding :Redeclaring a method in the base class with the extended class isknown as overriding.Encapsulation :Hiding of the properties and methods of a class using access specifiers(public,private and protected) is known as Encapsulation.Access Specifiers :These are prereserved keywords which are used for controlling thevisibility of properties and methods.They are public,protected andprivate.Public : A Public property or method which can be accessed orexecuted through the object and method of same class or through themethod of extended class.Protected : A Protected property or method which can be accessedthrough method of same class or extended class(They are notaccessible through object of same class or extended class).
  • 155.
    155Private : APrivate property or method which can be accessedthrough the method of same class.(It cannot be accessed throughobject of parent or child class and through method of child class).|object of |Method of| Object of | Method of ||same class|same class|extended class |Extended class |---------------------------------------------------------------------------------Public | Yes | Yes | Yes | Yes |---------------------------------------------------------------------------------Protected | No | Yes | No | Yes |---------------------------------------------------------------------------------Private | No | Yes | No | No |---------------------------------------------------------------------------------Ex :<?phpclass A{public $pub="public property<br>";protected $pro="protected property<br>";private $pri="private property<br>";public function pub(){"public Method<br>";}protected function pub(){"protected Method<br>";
  • 156.
    156}private function pub(){"privateMethod<br>";}function accessAll(){echo "<b>Method of same class</b><br>";echo $this->pub;echo $this->pro;echo $this->pri;echo $this->pub();echo $this->pro();echo $this->pri();}}class B extends A{function accessAllB{echo "<hr><b>Method of Extended class</b><br>";echo $this->pub;echo $this->pro;echo $this->pri; //noecho $this->pub();echo $this->pro();
  • 157.
    157echo $this->pri();//no}}$a=new A;//Objectof same classecho "<b>Object of same class</b><br>";echo $a->pub;echo $this->pro; //noecho $this->pri; //noecho $this->pub();echo $this->pro();//noecho $this->pri();//no$a->accessAll();$b=new B; //Object of extended classecho "<b>Object of extended class</b><br>";echo $b->pub;echo $b->accessAllB();?>Static :It is a predefined keyword used for declaring static properties ormethods. A property defined as static can be accessed through scoperesolution operator. It cannot be accessed through object instance. Astatic method must be executed through scope resolution operator(::).A static method should not use $this keyword inside its code.Final : It is a predefined keyword used for specifying a class as finalor a method as final.
  • 158.
    158Final class :A class specified as final cannot be extended to otherclass.Final method: A method specified as final cannot be overridden inextended class.Abstraction : abstract is a predefined keyword which is used fordefining abstract class or method.Abstract class : A class with atleast one abstract method must bedeclared as abstract class. An abstract class cannot be instantiateddirectly. An abstract class must be extended where abstract methodsmust be implemented with the code. An abstract class can haveproperties and constants. An abstract class should not contain privatemethods.Abstract methods : An abstract method should not contain body. Anabstract method cannot be private. abstract method must be declaredin its extended class along with its code.Ex: -<?phpabstract class a{public $x=10;const X=12;function abs(){echo "abstract method<br>";}}class B extends A{function abs(){echo "abstract method of extende class<br>";}
  • 159.
    159}?>Interface :An interfaceis a collection of bodyless method without any accessspecifier. An interface won't allows the usage of declaration ofproperties or normal methods. An interface cannot be instantiateddirectly whereas it can be implemented by a class. The class whichimplements the interface must redeclare its bodyless methods in theclass. Multiple interfaces can be implemented by a class.Implements : It is a predefined keyword which is used for loading aninterface to a class.
  • 160.
  • 161.
    161AJAXAJAX stands forAsynchronous JavaScript And XML. It is a clientside JavaScript method which is used for communication with theserver machine without any page refresh.1. To achieve asynchronous communication between browser andserver2. Updation of certain portions of the current webpage withoutReloading the entire webpage.AJAX is introduced in 2000 by Microsoft,it became very popularFrom 2005 onwards.AJAX is a browser dependent client side coding which is used forgetting the dynamic content from the server for JavaScript event inthe WebPages.AJAX communication will takes place in few steps.1. Creating a cross browser compatible AJAX.2. Opening the request to the server page.3. Sending the request.4. Checking the status of the request.5. On compilation of request loading the responded contentat the target element.Object in Internet Explorer :new ActiveXObject('Microsoft.XMLHTTP');new ActiveXObject('MSXML.XMLHTTP');new ActiveXObject('MSXML2.XMLHTTP');new ActiveXObject('MSXML3.XMLHTTP');new ActiveXObject('MSXMLC.XMLHTTP');
  • 162.
    162Other than IE:new XMLHttpRequest();Opening Request :if(window.ActiveXObject){document.write("IE");}else if(window.XMLHttpRequest){document.write("Other than IE");}else {document.write("No Ajax support");}Open :open(method,url,async,[user_name],[password]);Ex : ajax.open("Get","getuser.php?id=2",true);Sending the Request :Send :send(null|<parameters>)Ex:-send(ajax.send(null);Properties of AJAX :a) Ready State :0uninitialised(Ajax engine is created,connection is not established)1initialised(open method will be called,connection established)
  • 163.
    1632sent(send method iscalled,request is sent to server)3loading(request is under process)4completed(response received,process by AJAX engine completed)b) On ready state Change :Predefined event which will be called whenever ready state propertyvalue is updated.Ex :ajax.onreadystatechange=function(){if(ajax.readystate==4){document.write("ready state"<br>");}else{document.write("Not ready state<br>");}}c) Status :Here we will have the status code of the AJAX.200-> successful5xx->server issue4xx->page issue3xx->redirection
  • 164.
    164d) Response Text:The information send from the server as text content.ajax.responseTexte) ResponseXML :Used for accessing response XML.ajax.responseXMLFlow of AJAX based Application :1. User action is performed on any of the HTML components Likebutton, hyperlink, selectbox, textbox etc.2. Certain JavaScript event is raised because of the above User action3. Specific user defined JavaScript function is called to handle Theabove raised JavaScript event.4. In the above JavaScript function Logic is written to create Ajax engine Partial form data is gathered Callback (user-defined) function is set toonreadystatechange Property of AJAX engine. URL is prepared along with every string Connection is established (open method is called) Request is sent to server (send () is called)5. Request related response comes to AJAX engine as text or XMLdata.6. Once again callback function is called. Inside callback function Logic to take response received by AJAX engine usingJavaScript Logic is written to update certain portions of thecurrentwebpages without reloading the entire webpagewith the receiver response.
  • 165.
  • 166.
    166JOOMLAJOOMLA is acontent management system. It is a CMS tool. It isdeveloped on php using mysql as its backend.JOOMLA is a objectoriented based tool which was developed on the Top of MVCarchitecture. JOOMLA comes with various predefined templates,components, modules, languages And plug-ins.JOOMLA software is available in various versions. (JOOMLA1.0.x,JOOMLA1.5.x, JOOMLA1.6.x).JOOMLA software consists of two interfaces.1. User interface (front end)2. Admin interface (Backend)1. User Interface : Front end is the actual website Which is shown tothe actual users of the website.2. Admin interface : Backend is the interface Which is accessiblefor the backend users for Managing the website with various actions.User Management :It allows the management of the Users to the website. Various typesof users are observed.a)Front end users : Registeredb)Special users : Editor, Publisherc)Backend users : Manager, Adminstrator, Super administrator.Media Management :It is used for managing media files in the software.Section management :Section : It is a top level hierarchy for content Classification. Itallows the management of sections.Category management :
  • 167.
    167A category isthe child category for a section used for sub classifyingthe content.Article Management :It can be considered as a webpage In the site which can be classifiedto a category Or a section.Component : A component is a functional block in the Websitewhich can be considered as Database Interaction and can be loaded atthe main (center) Portion of the website.Module : It is a functional block which can occupy various pre-defined positions in the software like top,left,right ,user 1,user 2, …..user n, footer etc. A module can be controlled for its display in One ormore pages.Plug-in : A plug-in is a logical part which will Enhance the way inwhich we will display the Content of the website.Template management :A template is a predefined Interface which is used for switching theuser Interfaces on the fly.Language management :JOOMLA supports multilingual Sites where we can install languageextension for Adding support with additional language.www.joomla.orgLatest version is 1.7Installation of JOOMLA :1. Install joomla without sample data2. Add all the users for each role3. Create few categories4. Create few articles.5. Add the menu links for the articles category
  • 168.
    1686. Download freeJOOMLA templates and install switch between thetemplates.7. Try to change logo of the template8. Install the external modules and plug-ins9. Activate free loaded modules and plug-ins.Check theirfunctionality10. create a website with few links using JOOMLA
  • 169.
  • 170.
    170JQUERYJQuery is aJavaScript framework which is used For writing less codeand doing more action . JQuery is developed on top of java platformand it is used for creating rich website interface . JQuery is a fast andconcise JavaScript library . That simplifies HTML documenttraversing , event Handling, animating and Ajax interaction forRapid web development . JQuery is designed to Change the way thatyou write JavaScript.www.jquery.comSyntax :$(selector).methodSpecial Effects :Hide ()Show ()JQueryJQuery documentsJQuery core selectorJQuery supports css page selectorTraversingCSSEffectsEventsAJAX : implements JQuery plug-insUse JQuery pop calendarWrite JQuery cursorsJQuery based tool tips
  • 171.
    171JQuery based lightboxJQuery based form validationsJQuery based news agrigation using AJAXTHE END
  • 172.
  • 173.
    173Javascrtipt_Interview_Quesions1) <script type="text/javascript">x=4+"4";document.write(x);</script>Output------?a)44b) 8c) 4d) Error outputAns: a2) <script type="text/javascript" language="javascript">var qpt = "Vempower Solutions";var result = qpt.split(" ");document.write(result);</script>a) Vempowerb) V,e,m,p,o,w,e,r, S,o,l,u,t,I,o,n,sc) Vempower Solutionsd) VempoweSolutionsAns: c3) Is it possible to nest functions in JavaScript?a) Trueb) FalseAns: a
  • 174.
    1744) <script>document.write(navigator.appCodeName);</script>a) getcode name of the browser of a visitorb) set code name of the browser of a visitorc) None of the aboveAns: a5) Which of the following is true?a) If onKeyDown returns false, the key-press event is cancelled.b) If onKeyPress returns false, the key-down event is cancelled.c) If onKeyDown returns false, the key-up event is cancelled.d) If onKeyPress returns false, the key-up event is canceled.Ans: a6) Scripting language area) High Level Programming languageb) Assembly Level programming languagec) Machine level programming languageAns: a7) <script language="javascript">function x(){var s= "Good 100%";var pattern = /D/g;var output= s.match(pattern);document.write(output);}</script>
  • 175.
    175a) Good %b)1,0,0c) G,o,o,d,%d) ErrorAns: c8) <script language="javascript">var qpt="Sample String ";alert(qpt.charAt(qpt.length-1));</script>a) pb) ec) gd) ErrorAns: c9) Are java and javascript the same?a) NOb) YESAns: a10) Syntax for creating a RegExp object:(a). var txt=new RegExp(pattern,attributes);(b). var txt=/pattern/attributes;Which of the above mentioned syntax will correct?a) (a) onlyb) (b) onlyc) Both (a) and (b)d) None of the above
  • 176.
    176Ans: c11) <scriptlanguage="javascript">function x(z,t){alert(x.length);}</script>output:?a) Errorb) 2c) 1d) 3Ans: b12) What is mean by "this" keyword in javascript?a) It refers current objectb) It referes previous objectc) It is variable which contains valued) None of the aboveAns: a13) In JavaScript, Window.prompt() method return true or false value?a) Falseb) Truec) None of aboveAns: a14) Math. round(-20.51)=?a) 20
  • 177.
    177b) -21c) 19d)NoneAns: b15) <script language="javascript">function x(){var s = "Quality 100%!{[!!";var pattern = /w/g;var output = s.match(pattern);document.write(output);}</script>a) %,!,{,[,!,!b) Q,u,a,l,i,t,y,1,0,0c) Quality 100d) ErrorAns: b16) <script type="text/javascript" language="javascript">var qpt= new Array();qpt[0] = "WebDevelopment";qpt[1]="ApplicationDevelopment"qpt[2]="Testing"qpt[3] = "Vempower Solutions";document.write(qpt[0,1,2,3]);</script>a) Errorb) Vempower Solutionc) WebDevelopmentd) WebDevelopmnet,ApplicationDevelopment,Testing,VempowerSolutions
  • 178.
    178Ans: b17) parseFloat(9+10)=?a)19b) 910c) NoneAns: c18) <script language="javascript">function x(){document.write(2+5+"8");}</script>a) 258b) Errorc) 7d) 78Ans: d19) In Javascript, Which of the following method is used to evaluatethe regular expression?a) eval(2*(3+5))b) evaluate(2*(3+5))c) evalu(2*(3+5))d) None of the aboveAns: a20) <script language="javascript">function x(){var s= "quality 100%";
  • 179.
    179var pattern =/d/g;var output= s.match(pattern);document.write(output);}</script>a) 100b) 1,0,0c) q,u,a,l,i,t,y,%d) ErrorAns: b21) <script type="text/javascript" language="javascript">qpt=((45%2)==0)? "hello" : "bye";document.write(qpt);</script>a) hellob) byec) Error in string handlingd) None of the aboveAns: b22) How do you create a new object in JavaScript?a) var obj = {};b) var obj = Object();c) var obj=new {};d) None of the aboveAns: a23) In Javascript, What does isNaN function do ?a) Return true if the argument is not a number.b) Return false if the argument is not a number.
  • 180.
    180c) Return trueif the argument is a number.d) None of the aboveAns: a24) Which of the following properties hold the values of the pixels ofthe length of the width and height of the viewer's screen resolution?a) screen.width and screen.heightb) Resolution.width and Resolution.heightc) screen.pixels.width and screen.pixels.heightd) ViewerScreen.width and ViewerScreen.heightAns: a25)How to assign a function to a variable with the JavaScriptFunction contructor ?a) var f=Function("x","y","return x+y");b) var f=Function(x,y){ return x+y;}c) var f= new Function("x", "y", "return x + y");Ans: b26) In JavaScript, Window.alert() is used to allow user to entersomethinga) Trueb) Falsec) None of aboveAns: b27) Is Javascript has any date data type?a) Yesb) NoAns: b
  • 181.
    18128) ?_name isit valid javascript identifier?a) Yesb) NoAns: a29) <script type="text/javascript" language="javascript">var qpt="V-Empower Solutions ";var result =qpt.lastIndexOf("s");document.write(result);</script>a) -1b) 18c) 17d) 19Ans: 1830) <script language="javascript">function sum(x){function add(y){return x+y;}return add;}function callme() { result=sum(5)(5); alert(result); }</script>If you call the function callme(), what will happen ?a) 10b) Error in calling Functionc) 5
  • 182.
    182d) None ofthe aboveAns: a31) <script type="text/javascript">document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");</script>Can you write HTML tag inside the javascript ?a) Nob) Yesc) ImpossibleAns: b32) How to speicfy the color of the hypertext links with JavaScript ?a) document.linkColor="#00FF00";b) document.LColor="#00FF00";c) document.LinkC="#00FF00";d) document.hyperTextLink="#00FF00":Ans: a33) ------------- converts a string to floating point numbers.a) evalb) ParseIntc) ParseFloatd) NoneAns: c34) In Javascript, Which of the following method is used to find outthe character at a position in a string?a) charAt()
  • 183.
    183b) CharacterAt()c) CharPos()d)characAt()Ans: a35) <script type="text/javascript" language="javascript">var qpt = "V-Empower Solutions";var result =qpt.substring(7,8);document.write(result);</script>36) What are the following looping structures are available injavascripts?a) for,forecachb) foreach,whileloopc) do-while loop,foreachd) for , while loopAns: d37) Which of these is not a method of the Math object?a) atan()b) atan2()c) eval()d) acos()Ans: c38) <script type="text/javascript">var s = "9123456 or 80000?";var pattern = /d{4}/;var output = s.match(pattern);document.write(output);</script>
  • 184.
    184a) 9123b) 91234c)80000d) None of the aboveAns: a39) In javascript, RegExp Object Method test() is used to search astring and returnsa) true or falseb) found valuec) indexd) None of the aboveAns: a40) What property would you use to redirect a visitor to another page?a) document.URLb) window.location.hrefc) .document.location.hrefd) link.hrefAns: c41) -------------- method is used to remove focus from the specifiedobject.a) blur()b) focus()c) NoneAns: a42)Javascript is a ________ typed language.a) tightly
  • 185.
    185b) looselyAns: b43)Choosethe built-in object:a) Passwordb) Mathc) Linkd) HiddenAns: b44)Choose the object(s) associated with the onFocus event handler:a) Passwordb) Hiddenc) Bothd) NeitherAns: a45)Choose the object(s) associated with the onKeyPress eventhandler:a) Documentb) Layerc) Bothd) NeitherAns: a46)Choose the best pattern for the string: 840-21-3688a) /d+-d{2,}-?d*/b) /w+-w+-w+/c) /d+d+d+/d) /d+-d?-d+/
  • 186.
    186Ans: a47) Whichwould JavaScript assign to an uninitialized variable?a) NaNb) nullc) undefinedd) falseAns: c48)Which is not a built-in function?a) parseInt()b) exec()c) eval()d) parseFloat()Ans: b49)Seek the truth about setTimeOut():a) The statement(s) it executes run(s) only once.b) It pauses the script in which it is called.c) clearTimeOut() won't stop its execution.d) The delay is measured in hundredths of a second.Ans: a50)How do you call a function named "myFunction"?a) call function myFunctionb) myFunction()c) call myFunction()Ans: c51) What is the correct JavaScript syntax for opening a new windowcalled "window2" ?a)new("http://www.w3schools.com","window2")
  • 187.
    187b)new.window("http://www.w3schools.com","window2")c)window.open("http://www.w3schools.com","window2")d)open.new("http://www.w3schools.com","window2")Ans: c52)How doyou find the client's browser name?a)client.navNameb)browser.namec)navigator.appNameAns: c53) Semicolons are optional at the end of a JavaScript statement.a)Trueb)FalseAns: a54)Which of the following are capabilities of functions in JavaScript?a) Return a valueb) Accept parameters and Return a valuec) Accept parametersd) None of the aboveAns: c55)Which popup box you use when want a value from user beforeopen a page?a) alert("Write some text here")b) confirm("Write some text here")c) prompt("Write here some text")d) None of the aboveAns: c56)What is the correct way to write a JavaScript array?a) var txt = new Array("tim","kim","jim")b) var txt = new Array="tim","kim","jim"c) var txt = new Array:1=("tim")2=("kim")3=("jim")d) var txt = new Array(1:"tim",2:"kim",3:"jim")Ans: a57) How to submit form data with javascript?
  • 188.
    188a) document.formname.submit();b) submit()c)document.submit()d)None of the aboveAns: a58) When a user views a page containing a JavaScript program,which machine actually executes the script?a) The User's machine running a Web browserb) The Web serverc) A central machine deep within Netscape's corporate officesd) None of the aboveAns: a59) Which of the following is not a valid JavaScript variable name?a) 2namesb) _first_and_last_namesc) FirstAndLastd) None of the aboveAns:a60) To set up the window to capture all Click events, we use which ofthe following statement?a) window.captureEvents(Event.CLICK);b) window.handleEvents (Event.CLICK);c) window.routeEvents(Event.CLICK );d) window.raiseEvents(Event.CLICK ); Ans: aPHP_Interview_questionsQuestion: 1 Who is the father of PHP?
  • 189.
    189Answer: Rasmus Lerdorfis known as the father of PHP.Question: 2 What is the difference between $name and $$name?Answer: $name is variable where as $$name is reference variablelike $name=sonia and $$name=singh so $sonia value is singh.Question: 3 How can we submit a form without a submit button?Answer: 3 Java script submit () function is used for submit formwithout submit buttonon click call document.formname.submit()Question : 4 In how many ways we can retrieve the data in theresult set ofMySQL using PHP?Answer : 4 We can do it by 4 Ways1. mysql_fetch_row.2. mysql_fetch_array3. mysql_fetch_object4. mysql_fetch_assocQuestion : 5 What is the difference between mysql_fetch_objectandmysql_fetch_array?Answer : 5 mysql_fetch_object() is similar tomysql_fetch_array(),with one difference -an object is returned, instead of an array. Indirectly, that means thatyou can only access the data by the field names, and not by theiroffsets (numbers are illegal property names).Question : 6 What are the differences between get and postmethods.Answer : 6 There are some defference between GET and POSTmethod1. GET Method have some limit like only 2Kb data able to send forrequestBut in POST method unlimited data can we send
  • 190.
    1902. when weuse GET method requested data show in url butNot in POST method so POST method is good for send sensetiverequestQuestion : 7 How can we extract string "pcds.co.in " from astring "http://info@pcds.co.in using regular expression of PHP?Answer : 7preg_match("/^http://.+@(.+)$/","http://info@pcds.co.in",$matches);echo $matches[1];Question : 8 How can we create a database using PHP andMySQL?Answer : 8 We can create MySQL database with the use ofmysql_create_db("Database Name") .Question : 9 What are the differences between require andinclude?Answer : 9 Both include and require used to include a file but whenincluded file not found Include send Warning where as Require sendFatal Error .Question : 10 Can we use include ("xyz.PHP") two times in aPHP page "index.PHP"?Answer : 10 Yes we can use include("xyz.php") more than one timein any page. but it create a prob when xyz.php file contain somefuntions declaration then error will come for already declared functionin this file else not a prob like if you want to show same content twotime in page then must incude it two time not a prob.Question : 11 What are the different tables(Engine) present inMySQL, which one is default?Answer : 11 Following tables (Storage Engine) we can create.1. MyISAM(The default storage engine IN MYSQL Each MyISAMtable is stored on disk in three files. The files have names that beginwith the table name and have an extension to indicate the file type. An.frm file stores the table format. The data file has an .MYD (MYData)
  • 191.
    191extension. The indexfile has an .MYI (MYIndex) extension. )2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storageengine for MySQL that has commit, rollback, and crash-recoverycapabilities to protect user data.)3. Merge4. Heap (MEMORY)(The MEMORY storage engine creates tableswith contents that are stored in memory. Formerly, these were knownas HEAP tables. MEMORY is the preferred term, although HEAPremains supported for backward compatibility. )5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL withthe Berkeley DB transactional storage engine. This storage enginetypically is called BDB for short. BDB tables may have a greaterchance of surviving crashes and are also capable of COMMIT andROLLBACK operations on transactions)6. EXAMPLE7. FEDERATED (It is a storage engine that accesses data in tables ofremote databases rather than in local tables. )8. ARCHIVE (The ARCHIVE storage engine is used for storinglarge amounts of data without indexes in a very small footprint. )9. CSV (The CSV storage engine stores data in text files usingcomma-separated values format.)10. BLACKHOLE (The BLACKHOLE storage engine acts as a"black hole" that accepts data but throws it away and does not store it.Retrievals always return an empty result).Question : 12 What is use of header() function in php ?Answer : 12 The header() function sends a raw HTTP header to aclient.We can use herder() function for redirection of pages. It isimportant to notice that header() must be called before any actualoutput is seen.Question: 13 How can I execute a PHP script using commandline?Answer : 13 Just run the PHP CLI (Command Line Interface)program andprovide the PHP script file name as the command line argument.
  • 192.
    192Question : 14Suppose your Zend engine supports the mode <? ?>Then how can u configure your PHP Zend engine to support<?PHP ?> mode ?Answer : 14 In php.ini file: set short_open_tag=on to make PHPsupport .Question : 15 Shopping cart online validation i.e. how can weconfigure Paypal, etc.?Answer : 15 Nothing more we have to do only redirect to the payPalurl aftersubmit all information needed by paypal like amount,adresss etc.Question : 16 What is meant by nl2br()?Answer : 16 Inserts HTML line breaks (<BR />) before all newlinesin a string.Question : 17 What is htaccess? Why do we use this and Where?Answer : 17 .htaccess files are configuration files of Apache Serverwhich providea way to make configuration changes on a per-directory basis. A file,containing one or more configuration directives, is placed in aparticulardocument directory, and the directives apply to that directory, and allsubdirectories thereof.Question : 18 How we get IP address of client, previous referencepage etc?Answer : 18 By using$_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER']etc.Question : 19 What are the reasons for selecting lamp (Linux,apache, MySQL, PHP) instead of combination of other softwareprograms, servers and perating systems?Answer : 19 All of those are open source resource. Security of Linuxis very
  • 193.
    193very more thanwindows. Apache is a better server that IIS both infunctionality and security. MySQL is world most popular open sourcedatabase. PHP is more faster that asp or any other scripting language.Question : 20 How can we encrypt and decrypt a data present in aMySQL table using MySQL?Answer : 20 AES_ENCRYPT () and AES_DECRYPT ().Question : 21 How can we encrypt the username and passwordusing PHP?Answer : 21 The functions in this section perform encryption anddecryption, andcompression and uncompression:encryption DecryptionAES_ENCRYT() AES_DECRYPT()ENCODE() DECODE()DES_ENCRYPT() DES_DECRYPT()ENCRYPT() Not availableMD5() Not availableOLD_PASSWORD() Not availablePASSWORD() Not availableSHA() or SHA1() Not availableNot available UNCOMPRESSED_LENGTH()Question : 22 What are the features and advantages of object-orientedprogramming?
  • 194.
    194Answer : 22One of the main advantages of OO programming is itsease ofmodification; objects can easily be modified and added to a systemthereby reducing maintenance costs. OO programming is also consideredto bebetter at modeling the real world than is procedural programming. Itallows for more complicated and flexible interactions. OO systemsarealso easier for non-technical personnel to understand and easier forthem to participate in the maintenance and enhancement of a systembecause it appeals to natural human cognition patterns.For some systems, an OO approach can speed development time sincemanyobjects are standard across systems and can be reused. Componentsthatmanage dates, shipping, shopping carts, etc. can be purchased andeasilymodified for a specific system.Question : 23 What are the differences between procedure-oriented languages and object-oriented language?Answer : 23 There are lot of difference between procedure languageand object oriented like below1>Procedure language easy for new developer but complex tounderstand whole software as compare to object oriented model2>In Procedure language it is difficult to use design pattern mvc ,Singleton pattern etc but in OOP you we able to develop designpattern3>IN OOP language we able to ree use code like Inheritance,polymorphism etc but this type of thing not available in procedurelanguage on that our Fonda use COPY and PASTE .Question : 24 What is the use of friend function?Answer : 24 Sometimes a function is best shared among a number ofdifferentclasses. Such functions can be declared either as member functions of
  • 195.
    195one class oras global functions. In either case they can be set to befriends of other classes, by using a friend specifier in the class thatis admitting them. Such functions can use all attributes of the classwhich names them as a friend, as if they were themselves members ofthatclass.A friend declaration is essentially a prototype for a member function,but instead of requiring an implementation with the name of that classattached by the double colon syntax, a global function or memberfunction of another class provides the match.Question : 25 What are the differences between public, private,protected,static, transient, final and volatile?Answer : 25 Public: Public declared items can be accessedeverywhere.Protected: Protected limits access to inherited and parentclasses (and to the class that defines the item).Private: Private limits visibility only to the class that definesthe item.Static: A static variable exists only in a local function scope,but it does not lose its value when program execution leaves thisscope.Final: Final keyword prevents child classes from overriding amethod by prefixing the definition with final. If the class itself isbeing defined final then it cannot be extended.transient: A transient variable is a variable that may notbe serialized.volatile: a variable that might be concurrently modified by multiplethreads should be declared volatile. Variables declared to be volatilewill not be optimized by the compiler because their value can changeatany time.Question : 26 What are the different types of errors in PHP?Answer : 26 Three are three types of errors:1. Notices: These aretrivial,
  • 196.
    196non-critical errors thatPHP encounters while executing a script –forexample, accessing a variable that has not yet been defined. Bydefault,such errors are not displayed to the user at all – although, as youwillsee, you can change this default behavior.2. Warnings: These aremore serious errors – for example, attemptingto include() a file which does not exist. By default, these errors aredisplayed to the user, but they do not result in script termination.3.Fatal errors: These are critical errors – for example,instantiating an object of a non-existent class, or calling anon-existent function. These errors cause the immediate terminationofthe script, and PHP's default behavior is to display them to the userwhen they take place.Question : 27 What is the functionality of the function strstr andstristr? Answer : 27 strstr Returns part of string from the firstoccurrence of needle(sub string that we finding out ) to the end ofstring.$email= 'sonialouder@gmail.com';$domain = strstr($email, '@');echo $domain; // prints @gmail.comhere @ is the needlestristr is case-insensitive means able not able to differentiate betweena and A.Question : 28 What are the differences between PHP 3 and PHP 4and PHP 5?Answer : 28 There are lot of difference among these three version ofphp1.Php3 is oldest version after that php4 came and current version isphp5 (php5.3) where php6 have to come2.Difference mean oldest version have less functionality as compareto new one like php5 have all OOPs concept now where as php3 waspure procedural language constructive like CIn PHP5 1. Implementation of exceptions and exception handling
  • 197.
    1972. Type hintingwhich allows you to force the type of a specificargument3. Overloading of methods through the __call function4. Full constructors and destructors etc through a __constructor and__destructor function5. __autoload function for dynamically including certain include filesdepending on the class you are trying to create.6 Finality : can now use the final keyword to indicate that a methodcannot be overridden by a child. You can also declare an entire classas final which prevents it from having any children at all.7 Interfaces & Abstract Classes8 Passed by Reference :9 An __clone method if you really want to duplicate an object.Question : 29 How can we convert asp pages to PHP pages?Answer : 29 there are lots of tools available for asp to PHPconversion. you cansearch Google for that. the best one is availableathttp://asp2php.naken.cc./.Question : 30 What is the functionality of the functionhtmlentities? Answer : 30 Convert all applicable characters toHTML entitiesThis function is identical to htmlspecialchars() in all ways, exceptwith htmlentities(), all characters which have HTML character entityequivalents are translated into these entities.Question : 31 How can we get second of the current time usingdate function?Answer : 31 $second = date("s");Question : 32 How can we convert the time zones using PHP?Answer : 32 By using date_default_timezone_get anddate_default_timezone_set function on PHP 5.1.0<?php// Discover what 8am in Tokyo relates to on the East Coast of the US// Set the default timezone to Tokyo time:
  • 198.
    198date_default_timezone_set('Asia/Tokyo');// Now generatethe timestamp for that particular timezone, on Jan 1st,2000$stamp = mktime(8, 0, 0, 1, 1, 2000);// Now set the timezone back to US/Easterndate_default_timezone_set('US/Eastern');// Output the date in a standard format (RFC1123), this will print:// Fri, 31 Dec 1999 18:00:00 ESTecho '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>Question : 33 What is meant by urlencode and urldocode?Answer : 33 URLencode returns a string in which all non-alphanumeric charactersexcept -_. have been replaced with a percent (%) sign followed bytwo hex digits and spaces encoded as plus (+) signs. It is encoded thesame way that the posted data from a WWW form is encoded, that isthe same way as inapplication/x-www-form-urlencoded media type.urldecode decodes any %##encoding in the given string.Question : 34 What is the difference between the functions unlinkand unset?Answer : 34 unlink() deletes the given file from the file system.unset() makes a variable undefined.Question : 35 How can we register the variables into a session?Answer : 35 $_SESSION['name'] = "sonia";Question : 36 How can we get the properties (size, type, width,height) of an image using PHP image functions?Answer : 36 To know the Image type use exif_imagetype () functionTo know the Image size use getimagesize () functionTo know the image width use imagesx () functionTo know the image height use imagesy() function.
  • 199.
    199Question : 37How can we get the browser properties using PHP?Answer : 37 By using $_SERVER['HTTP_USER_AGENT']variable.Question : 38 What is the maximum size of a file that can beuploaded using PHP and how can we change this?Answer : 38 By default the maximum size is 2MB. and we canchange the followingsetup at php.ini upload_max_filesize = 2M.Question : 39 How can we increase the execution time of a PHPscript? Answer : 39 by changing the following setup at php.inimax_execution_time = 30; Maximum execution time of each script, in seconds.Question : 40 How can we take a backup of a MySQL table andhow can we restore it. ?Answer : 40 To backup: BACKUP TABLE tbl_name[,tbl_name…]TO'/path/to/backup/directory'. RESTORE TABLEtbl_name[,tbl_name…] FROM'/path/to/backup/directory'mysqldump: Dumping Table Structure andDataUtility to dump a database or a collection of database for backuporfor transferring the data to another SQL server (not necessarily aMySQLserver). The dump will contain SQL statements to create the tableand/orpopulate the table.Question : 41 How can we optimize or increase the speed of aMySQL selectquery?Answer : First of all instead of using select * from table1, use selectcolumn1, column2, column3.. from table1
  • 200.
    200 Look forthe opportunity to introduce index in the table you arequerying. Use limit keyword if you are looking for any specific number ofrows from the result set.Question : 42 How many ways can we get the value of currentsession id?Answer : 42 session_id() returns the session id for the currentsession.Question : 43 How can we destroy the session, how can we unsetthe variable of a session?Answer : 43 session_unregister to Unregister a global variable fromthe currentsession session_unset to Free all session variables.Question : 44 How can we set and destroy the cookie n php?Answer : 44 By using setcookie(name, value, expire, path, domain);function we can set the cookie in php ;Set the cookies in past for destroy. likesetcookie("user", "sonia", time()+3600); for set the cookiesetcookie("user", "", time()-3600); for destroy or delete the cookies;Question : 45 How many ways we can pass the variable throughthe navigation between the pages?Answer : 45. GET/QueryString POSTQuestion : 46 What is the difference between ereg_replace() anderegi_replace()?Answer : 46 eregi_replace() function is identical to ereg_replace()except thatthis ignores case distinction when matching alphabeticcharacters.eregi_replace() function is identical to ereg_replace()
  • 201.
    201except that thisignores case distinction when matching alphabeticcharacters.Question : 47 What are the different functions in sorting anarray?Answer : 47 Sort(), arsort(),asort(), ksort(),natsort(), natcasesort(),rsort(), usort(),array_multisort(), and uksort().Question : 48 How can we know the count/number of elements ofan array?Answer : 48 2 waysa) sizeof($urarray) This function is an alias of count()b) count($urarray)Question : 49 what is session_set_save_handler in PHP?Answer : 49 session_set_save_handler() sets the user-level sessionstorage functions which are used for storing and retrieving dataassociated with a session. This is most useful when a storage methodother than those supplied by PHP sessions is preferred. i.e. Storing thesession data in a local database.Question : 50 How can I know that a variable is a number or notusing aJavaScript?Answer : 50 bool is_numeric ( mixed var) Returns TRUE if var is anumber or a numeric string, FALSE otherwise.or use isNaN(mixedvar)The isNaN() function is used to check if a value is not a number.Question : 51 List out some tools through which we can draw E-Rdiagrams for mysql.Answer : 51 Case Studio Smart Draw.Question : 52 How can I retrieve values from one database serverand store them in other database server using PHP?Answer : 52 we can always fetch from one database and rewrite toanother. here
  • 202.
    202is a nicesolution of it.$db1 = mysql_connect("host","user","pwd")mysql_select_db("db1", $db1);$res1 = mysql_query("query",$db1);$db2 =mysql_connect("host","user","pwd")mysql_select_db("db2", $db2);$res2 = mysql_query("query",$db2);At this point you can only fetchrecords from you previous ResultSet,i.e $res1 But you cannot execute new query in $db1, even if yousupply the link as because the link was overwritten by the new db.soat this point the following script will fail.$res3 = mysql_query("query",$db1); //this will failSo how to solvethat?take a look below.$db1 = mysql_connect("host","user","pwd")mysql_select_db("db1", $db1);$res1 = mysql_query("query",$db1);$db2 = mysql_connect("host","user","pwd", true)mysql_select_db("db2", $db2);$res2 = mysql_query("query",$db2);So mysql_connect has another optional boolean parameter whichindicates whether a link will be created or not. as we connect to the$db2 with this optional parameter set to 'true', so both link willremain live.now the following query will execute successfully.$res3 = mysql_query("query",$db1);Question : 53 List out the predefined classes in PHP?Answer : 53 Directory stdClass __PHP_Incomplete_Class exceptionphp_user_filter.Question : 54 How can I make a script that can be bi-language(supportsEnglish, German)?
  • 203.
    203Answer : 54You can maintain two separate language file for each ofthelanguage. all the labels are putted in both language files as variablesand assign those variables in the PHP source. on runtime choose therequired language option.Question : 55 What are the difference between abstract class andinterface?Answer : 55 Abstract class: abstract classes are the class where oneor moremethods are abstract but not necessarily all method has to be abstract.Abstract methods are the methods, which are declare in its class butnotdefine. The definition of those methods must be in its extendingclass.Interface: Interfaces are one type of class where all the methodsareabstract. That means all the methods only declared but not defined.Allthe methods must be define by its implemented class.Question : 56 How can we send mail using JavaScript?Answer : 56 JavaScript does not have any networking capabilities asit isdesigned to work on client site. As a result we can not send mailsusingJavaScript. But we can call the client side mail protocol mailtovia JavaScript to prompt for an email to send. this requires the clientto approve it.Question : 57 How can we repair a MySQL table?Answer : 57 The syntex for repairing a MySQL table isREPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]This command will repair the table specified if the quick is given theMySQL will do a repair of only the index tree if the extended is givenit will create index row by row.Question : 58 What are the advantages of stored procedures,triggers, indexes?
  • 204.
    204Answer : 58A stored procedure is a set of SQL commands that canbe compiled and stored in the server. Once this has been done, clientsdon't need tokeep re-issuing the entire query but can refer to the stored procedure.This provides better overall performance because the query has to beparsed only once, and less information needs to be sent between theserver and the client. You can also raise the conceptual level byhavinglibraries of functions in the server. However, stored procedures ofcourse do increase the load on the database server system, as more ofthe work is done on the server side and less on the client (application)side.Triggers will also be implemented. A trigger is effectively a typeofstored procedure, one that is invoked when a particular event occurs.For example, you can install a stored procedure that is triggered eachtime a record is deleted from a transaction table and that storedprocedure automatically deletes the corresponding customer from acustomer table when all his transactions are deleted.Indexes are usedto find rows with specific column values quickly.Without an index, MySQL must begin with the first row and then readthrough the entire table to find the relevant rows. The larger thetable, the more this costs. If the table has an index for the columns inquestion, MySQL can quickly determine the position to seek to in themiddle of the data file without having to look at all the data. If atable has 1,000 rows, this is at least 100 times faster than readingsequentially. If you need to access most of the rows, it is faster toread sequentially, because this minimizes disk seeks.Question : 59 What is the maximum length of a table name,database name, and fieldname in MySQL?Answer : 59 The following table describes the maximum length foreach type ofidentifier.IdentifierMaximum Length(bytes)
  • 205.
    205Database 64Table 64Column64Index 64Alias 255There are some restrictions on the characters that may appear inidentifiers:Question : 60 How many values can the SET function of MySQLtake?Answer : 60 MySQL set can take zero or more values but at themaximum it cantake 64 values.Question : 61 What are the other commands to know thestructure of table using MySQL commands except explaincommand?Answer : 61 describe Table-Name;Question : 62 How many tables will create when we create table,what are they?Answer : 62 The '.frm' file stores the table definition.The data file has a '.MYD' (MYData) extension.The index file has a '.MYI' (MYIndex) extension.Question : 63 What is the purpose of the following files havingextensions 1) .frm 2) .myd 3) .myi? What do these files contain?Answer : 63 In MySql, the default table type is MyISAM.Each MyISAM table is stored on disk in three files. The files havenamesthat begin with the table name and have an extension to indicate thefile type.The '.frm' file stores the table definition.
  • 206.
    206The data filehas a '.MYD' (MYData) extension.The index file has a '.MYI' (MYIndex) extension.Question : 64 What is maximum size of a database in MySQL?Answer : 64 If the operating system or filesystem places a limit onthe numberof files in a directory, MySQL is bound by that constraint.Theefficiency of the operating system in handling large numbers of filesin a directory can place a practical limit on the number of tables in adatabase. If the time required to open a file in the directory increasessignificantly as the number of files increases, databaseperformance can be adversely affected. The amount of available diskspace limits the number of tables.MySQL 3.22 had a 4GB (4gigabyte) limit on table size. With the MyISAM storage engine inMySQL 3.23, the maximum table size was increased to65536 terabytes (2567 – 1 bytes). With this larger allowed tablesize,the maximum effective table size for MySQL databases is usuallydetermined by operating system constraints on file sizes, not byMySQL internal limits.The InnoDB storage engine maintains InnoDBtables within a tablespace that can be created from several files. Thisallows a table to exceed the maximum individual file size. Thetablespace can include raw disk partitions, which allows extremelylarge tables. The maximum tablespace size is 64TB. The followingtable lists some examples of operating system file-sizelimits. This isonly a rough guide and is not intended to be definitive.For the mostup-to-date information, be sure to check the documentationspecific to your operating system.Operating System File-size.LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB) Linux 2.4+ (using ext3filesystem) 4TBSolaris 9/10 16TBNetWare w/NSS filesystem 8TBWin32 w/ FAT/FAT32 2GB/4GBWin32 w/ NTFS 2TB (possibly larger)MacOS X w/ HFS+ 2TB.Question : 65 Give the syntax of Grant and Revoke commands?Answer : 65 The generic syntax for grant is as followingGRANT [rights] on [database/s] TO [username@hostname]
  • 207.
    207IDENTIFIED BY [password]now rights can bea) All privilegesb) combination of create, drop, select, insert, update and delete etc.Wecan grant rights on all databse by using *.* or some specificdatabase by database.* or a specific table by database.table_nameusername@hotsname can be either username@localhost,username@hostnameand username@%where hostname is any valid hostname and % represents any name,the *.*any conditionpassword is simply the password of userThe generic syntax for revokeis as followingREVOKE [rights] on [database/s] FROM [username@hostname] nowrights can be as explained abovea) All privilegesb) combination of create, drop, select, insert, update and delete etc.username@hotsname can be either username@localhost,username@hostnameand username@%where hostname is any valid hostname and % represents any name,the *.*any conditionQuestion : 66 Explain Normalization concept?Answer : 66 The normalization process involves getting our data toconform tothree progressive normal forms, and a higher level of normalizationcannot be achieved until the previous levels have been achieved (thereare actually five normal forms, but the last two are mainly academicandwill not be discussed).First Normal FormThe First Normal Form (or1NF) involves removal of redundant datafrom horizontal rows. We want to ensure that there is no duplicationofdata in a given row, and that every column stores the least amount ofinformation possible (making the field atomic).Second Normal
  • 208.
    208FormWhere the FirstNormal Form deals with redundancy of dataacross ahorizontal row, Second Normal Form (or 2NF) deals with redundancyofdata in vertical columns. As stated earlier, the normal forms areprogressive, so to achieve Second Normal Form, your tables mustalreadybe in First Normal Form.Third Normal FormI have a confession to make; I do not often use Third Normal Form. InThird Normal Form we are looking for data in our tables that is notfully dependant on the primary key, but dependant on another value inthe tableQuestion : 67 How can we find the number of rows in a tableusing MySQL? Answer : 67 Use this for mysql SELECTCOUNT(*) FROM table_name;Question : 68 How can we find the number of rows in a result setusing PHP?Answer : 68 $result = mysql_query($sql, $db_link);$num_rows = mysql_num_rows($result);echo "$num_rows rows found";Question : 69 How many ways we can we find the current dateusing MySQL?Answer : 69 SELECT CURDATE();CURRENT_DATE() = CURDATE()for time useSELECT CURTIME();CURRENT_TIME() = CURTIME()Question : 70 What are the advantages and disadvantages ofCascading Style Sheets?Answer : 70 External Style SheetsAdvantagesCan control styles formultiple documents at once. Classes can be created for use onmultiple HTML element types in many documents. Selector andgrouping methods can be used to apply styles under complex
  • 209.
    209contextsDisadvantagesAn extra downloadis required to import styleinformation for each document The rendering of the document maybe delayed until the external style sheet is loaded Becomes slightlyunwieldy for small quantities ofstyle definitions Embedded StyleSheets Advantages Classes can be created for use on multiple tagtypes in the document. Selector and grouping methods can be used toapply styles under complex contexts. No additional downloadsnecessary to receive style informationDisadvantagesThis method can not control styles for multiple documents at onceInline StylesAdvantagesUseful for small quantities of style definitions. Can override otherstyle specification methods at the local level so only exceptions needto be listed in conjunction with other style methods.DisadvantagesDoes not distance style information from content (a main goal ofSGML/HTML). Can not control styles for multiple documents atonce. Author can not create or control classes of elements to controlmultiple element types within the document. Selector groupingmethods can not be used to create complex element addressingscenariosQuestion : 71 What type of inheritance that PHP supports?Answer : 71 In PHP an extended class is always dependent on asingle base class,that is, multiple inheritance is not supported. Classes are extendedsing the keyword 'extends'.Question : 72 What is the difference between Primary Key andUnique key?
  • 210.
    210Answer : 72Primary Key: A column in a table whose valuesuniquely identify therows in the table. A primary key value cannot be NULL.Unique Key: Unique Keys are used to uniquely identify each row inthe table. There can be one and only one row for each unique keyvalue. So NULL can be a unique key.There can be only one primarykey for a table but there can be more than one unique for a table.Question : 73 what is garbage collection? default time ? refreshtime?Answer : 73 Garbage Collection is an automated part of PHP , If theGarbage Collection process runs, it then analyzes any files in the /tmpfor any session files that have not been accessed in a certain amountof time and physically deletes them. Garbage Collection process onlyruns in the default session save directory, which is /tmp. If you opt tosave your sessions in a different directory, the Garbage Collectionprocess will ignore it. the Garbage Collection process does notdifferentiate between which sessions belong to whom when run. Thisis especially important note on shared web servers. If the process isrun, it deletes ALL files that have not been accessed in the directory.There are 3 PHP.ini variables, which deal with the garbage collector:PHP ini value name default session.gc_maxlifetime 1440 seconds or24 minutes session.gc_probability 1 session.gc_divisor 100.Question : 74 What are the advantages/disadvantages of MySQLand PHP? Answer : 74 Both of them are open source software (sofree of cost), supportcross platform. php is faster then ASP and JSP.Question : 75 What is the difference between GROUP BY andORDER BY in Sql? Answer : 75 ORDER BY[col1],[col2],…,[coln]; Tels DBMS according to what columns itshould sort the result. If two rows will hawe the same value in col1it will try to sort them according to col2 and so on.GROUP BY[col1],[col2],…,[coln]; Tels DBMS to group results with same valueofcolumn col1. You can use COUNT(col1), SUM(col1), AVG(col1)
  • 211.
    211with it, ifyouwant to count all items in group, sum all values or view average.Question : 76 What is the difference between char and varchardata types? Answer : 76 Set char to occupy n bytes and it will take nbytes even if u r storing a value of n-m bytes Set varchar to occupy nbytes and it will take only the required space and will not use the nbyteseg. name char(15) will waste 10 bytes if we store 'romharshan', if eachchartakes a byteeg. name varchar(15) will just use 5 bytes if we store 'romharshan', ifeachchar takes a byte. rest 10 bytes will be free.Question : 77 What is the functionality of md5 function in PHP?Answer : 77 Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use toidentify users etc. If I add random no techniques to it the md5generated nowwill be totally different for the same string I am using.Question : 78 How can I load data from a text file into a table?Answer : 78 you can use LOAD DATA INFILE file_name; syntax toload data from a text file. but you have to make sure thata) data isdelimited b) columns and data matched correctly.Question : 79 How can we know the number of days between twogiven dates using MySQL?Answer : 79 SELECT DATEDIFF("2007-03-07","2005-01-01");Question : 80 How can we know the number of days between twogiven dates using PHP?Answer : 80 $date1 = date("Y-m-d");$date2 = "2006-08-15";$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);Question : 81 How we load all classes that placed in differentdirectory in one PHP File , means how to do auto load classes.
  • 212.
    212Answer : 81byusing spl_autoload_register('autoloader::funtion');Like belowclass autoloader{public static function moduleautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] ."/modules/{$class}.php";if (is_readable($path)) require $path;}public static function daoautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] ."/dataobjects/{$class}.php";if (is_readable($path)) require $path;}public static function includesautoloader($class){$path = $_SERVER['DOCUMENT_ROOT'] ."/includes/{$class}.php";if (is_readable($path)) require $path;}}spl_autoload_register('autoloader::includesautoloader');spl_autoload_register('autoloader::daoautoloader');spl_autoload_register('autoloader::moduleautoloader');Question : 82 How many types of Inheritances used in PHP andhow we achieve it.
  • 213.
    213Answer : 82As far PHP concern it only support single Inheritance inscripting.we can also use interface to achieve multiple inheritance.Question : 83 PHP how to know user has read the email?Answer : 83 Using Disposition-Notification-To: in mailheader wecan get read receipt.Add the possibility to define a read receipt whensending an email.It’s quite straightforward, just edit email.php, and add this at varsdefinitions:var $readReceipt = null;And then, at ‘createHeader’ function add:if (!empty($this->readReceipt)) {$this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine;}Question : 84 What are default session time and path?Answer : 84 default session time in PHP is 1440 seconds or 24minutesDefault session save path id temporary folder /tmp.Question : 85 how to track user logged out or not? when user isidle ? Answer : 85 By checking the session variable exist or notwhile loading th page. As the session will exist longer as till browsercloses. The default behaviour for sessions is to keep a session openindefinitely and only to expire a session when the browser is closed.This behaviour can be changed in the php.ini file by altering the linesession.cookie_lifetime = 0 to a value in seconds. If you wanted thesession to finish in 5 minutes you would set this tosession.cookie_lifetime = 300 and restart your httpd server.Question : 86 how to track no of user logged in ?Answer : 86 whenever a user logs in track the IP, userID etc..andstore it in a DB with a active flag while log out or sesion expire makeit inactive. At any time by counting the no: of active records we canget the no: of visitors.
  • 214.
    214Question : 87in PHP for pdf which library used?Answer : 87 The PDF functions in PHP can create PDF files usingthe PDFlib library With version 6, PDFlib offers an object-orientedAPI for PHP 5 in addition to the function-oriented API for PHP 4.There is also the » Panda module. FPDF is a PHP class whichallows to generate PDF files with pure PHP, that is to say withoutusing the PDFlib library. F from FPDF stands for Free: you may use itfor any kind of usage and modify it to suit your needs. FPDF requiresno extension (except zlib to activate compression and GD for GIFsupport) and works with PHP4 and PHP5.Question : 88 for image work which library?Answer : 88 we will need to compile PHP with the GD library ofimage functions for this to work. GD and PHP may also require otherlibraries, depending on which image formats you want to work with.Question : 89 what is design pattern? singleton pattern?Answer : 89 A design pattern is a general reusable solution to acommonly occurring problem in software design. The Singletondesign pattern allows many parts of a program to share a singleresource without having to work out the details of the sharingthemselves.Question : 90 what are magic methods?Answer : 90 Magic methods are the members functions that isavailable to all the instance of class Magic methods always starts with"__". Eg. __construct All magic methods needs to be declared aspublic To use magic method they should be defined within the classor program scope Various Magic Methods used in PHP 5 are:__construct() __destruct() __set() __get() __call() __toString()__sleep() __wakeup() __isset() __unset() __autoload() __clone().Question : 91 what is magic quotes?Answer : 91 Magic Quotes is a process that automatically escapesincoming data to the PHP script. It’s preferred to code with magicquotes off and to instead escape the data at runtime, as needed. This
  • 215.
    215feature has beenDEPRECATED as of PHP 5.3.0 and REMOVED asof PHP 6.0.0. Relying on this feature is highly discouraged.Question : 92 what is cross site scripting? SQL injection?Answer : 92 Cross-site scripting (XSS) is a type of computer securityvulnerability typically found in web applications which allow codeinjection by malicious web users into the web pages viewed by otherusers. Examples of such code include HTML code and client-sidescripts. SQL injection is a code injection technique that exploits asecurity vulnerability occurring in the database layer of anapplication. The vulnerability is present when user input is eitherincorrectly filtered for string literal escape characters embedded inSQL statements or user input is not strongly typed and therebyunexpectedly executed.Question : 93 what is URL rewriting?Answer : 93 Using URL rewriting we can convert dynamic URl tostatic URL Static URLs are known to be better than Dynamic URLsbecause of a number of reasons 1. Static URLs typically Rank betterin Search Engines. 2. Search Engines are known to index the contentof dynamic pages a lot slower compared to static pages. 3. StaticURLs are always more friendlier looking to the End Users. along withthis we can use URL rewriting in adding variables [cookies] to theURL to handle the sessions.Question : 94 what is the major php security hole? how to avoid?Answer : 94 1. Never include, require, or otherwise open a file with afilename based on user input, without thoroughly checking it first.2. Be careful with eval() Placing user-inputted values into the eval()function can be extremely dangerous. You essentially give themalicious user the ability to execute any command he or she wishes!3. Be careful when using register_globals = ON It was originallydesigned to make programming in PHP easier (and that it did), butmisuse of it often led to security holes4. Never run unescaped queries5. For protected areas, use sessions or validate the login every time.
  • 216.
    2166. If youdon’t want the file contents to be seen, give the file a .phpextension.Question : 95 whether PHP supports Microsoft SQL server ?Answer : 95 The SQL Server Driver for PHP v1.0 is designed toenable reliable, scalable integration with SQL Server for PHPapplications deployed on the Windows platform. The Driver for PHPis a PHP 5 extension that allows the reading and writing of SQLServer data from within PHP scripts. using MSSQL or ODBCmodules we can access Microsoft SQL server.Question : 96 what is MVC? why its been used?Answer : 96 Model-view-controller (MVC) is an architectural patternused in software engineering. Successful use of the pattern isolatesbusiness logic from user interface considerations, resulting in anapplication where it is easier to modify either the visual appearance ofthe application or the underlying business rules without affecting theother. In MVC, the model represents the information (the data) of theapplication; the view corresponds to elements of the user interfacesuch as text, checkbox items, and so forth; and the controller managesthe communication of data and the business rules used to manipulatethe data to and from the model. WHY ITS NEEDED IS 1 Modularseparation of function 2 Easier to maintain 3 View-Controllerseparation means:A Tweaking design (HTML) without altering code B Web designstaff can modify UI without understanding code.Question : 97 what is framework? how it works? what isadvantage? Answer : 97 In general, a framework is a real orconceptual structure intended to serve as a support or guide for thebuilding of something that expands the structure into somethinguseful. Advantages : Consistent Programming Model Direct Supportfor Security Simplified Development Efforts Easy ApplicationDeployment and Maintenance.Question : 98 what is CURL?Answer : 98 CURL means Client URL Librarycurl is a command line tool for transferring files with URL syntax,
  • 217.
    217supporting FTP, FTPS,HTTP, HTTPS, SCP, SFTP, TFTP, TELNET,DICT, LDAP, LDAPS and FILE. curl supports SSL certificates,HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload,proxies, cookies, user+password authentication (Basic, Digest,NTLM, Negotiate), file transfer resume, proxy tunneling and abusload of other useful tricks. CURL allows you to connect andcommunicate to many different types of servers with many differenttypes of protocols. libcurl currently supports the http, https, ftp,gopher, telnet, dict, file, and ldap protocols. libcurl also supportsHTTPS certificates, HTTP POST, HTTP PUT, FTP uploading. HTTPform based upload, proxies, cookies, and user+passwordauthentication.Question : 99 what is PDO ?Answer : 99The PDO ( PHP Data Objects ) extension defines a lightweight,consistent interface for accessing databases in PHP. if you are usingthe PDO API, you could switch the database server you used, fromsay PgSQL to MySQL, and only need to make minor changes to yourPHP code. While PDO has its advantages, such as a clean, simple,portable API but its main disadvantage is that it doesn't allow you touse all of the advanced features that are available in the latest versionsof MySQL server. For example, PDO does not allow you to useMySQL's support for Multiple Statements.Just need to use below code for connect mysql using PDOtry {$dbh = new PDO("mysql:host=$hostname;dbname=databasename",$username, $password);$sql = "SELECT * FROM employee";foreach ($dbh->query($sql) as $row){print $row['employee_name'] .' - '. $row['employee_age'] ;}}catch(PDOException $e){
  • 218.
    218echo $e->getMessage();}Question :100 What is PHP's mysqli Extension ?Answer : 100The mysqli extension, or as it is sometimes known, the MySQLimproved extension, was developed to take advantage of new featuresfound in MySQL systems versions 4.1.3 and newer. The mysqliextension is included with PHP versions 5 and later.The mysqli extension has a number of benefits, the key enhancementsover the mysql extension being:=>Object-oriented interface=>Support for Prepared Statements=>Support for Multiple Statements=>Support for Transactions=>Enhanced debugging capabilitiesB.Praveen Kumar(Trainer in PHP)Sathya Technology,Ameerpete-mailid:praveen.lamp@gmail.comStudent e-mailid:ankushsuryawanshi9@gmail.com

[8]ページ先頭

©2009-2025 Movatter.jp