Sunday, October 16, 2011

JavaScript Interview Questions and Answers

1 :: What is JavaScript?
JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be--and is--used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content. JavaScript is a platform-independent, event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.

 2 :: What’s relationship between JavaScript and ECMAScript? 
ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 

3 :: How do you submit a form using JavaScript? 
Use document.forms[0].submit() (0 refers to the index of the form – if we have more than one form in a page, then the first one has the index 0, second has index 1 and so on). 

4 :: How to read and write a file using JavaScript? 
I/O operations like reading or writing a file is not possible with client-side JavaScript. However , this can be done by coding a Java applet that reads files for the script .

5 :: How to detect the operating system on the client machine? 
In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.

6 :: What are JavaScript Data Types? 
JavaScript Data Types are Number, String, Boolean, Function, Object, Null, Undefined 

7 :: How do you convert numbers between different bases in JavaScript? 
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt (" 3F" , 16) 

8 :: How to create arrays in JavaScript? 
We can declare an array like this var scripts = new Array()
We can add elements to this array like this scripts[0] = " PHP" scripts[1] = " ASP" scripts[2] = " JavaScript" scripts[3] = " HTML" Now our array scripts have 4 elements inside it and we can print or access them by using their index number.
Note that index number starts from 0. To get the third element of the array we have to use the index number 2. Here is the way to get the third element of an array. document.write(scripts[2]) We also can create an array like this var no_array = new Array(21, 22, 23, 24, 25) 

9 :: How do you target a specific frame from a hyperlink in JavaScript? 
Include the name of the frame in the target attribute of the hyperlink in JavaScript. < a href=”http://www.globalguideline.com” target=”myframe”> Global Guide Line< /a> 

10 :: What are a fixed-width table and its advantages in JavaScript?
Fixed width tables are rendered by the browser based on the widths of the columns in the first row, in JavaScript resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table. If the table is not specified to be of fixed width in JavaScript, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables. 

 11 :: Example of using Regular Expressions for syntax checking in JavaScript?
 var re = new RegExp(" ^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$" ) var text = myWidget.value var OK = re.test(text) if( ! OK ) { alert(" The extra parameters need some work. Should be something like: " &a=1&c=4" " ) } 

12 :: How to add Buttons in JavaScript? 
The most basic and ancient use of buttons are the " submit" and " clear" , which appear slightly before the Pleistocene period. Notice when the " GO!" button is pressed it submits itself to itself and appends the name in the URL.
< form action=" " name=" buttonsGalore" method=" get" >
Your Name: < input type=" text" name=" mytext" /> < br />
< input type=" submit" value=" GO!" />
< input type=" reset" value=" Clear All" /> < /form>
 Another useful approach is to set the " type" to " button" and use the " onclick" event.
< script type=" text/javascript" >
function displayHero(button) { alert(" Your hero is " " +button.value+" " ." ) }
< /script> 
< form action=" " name=" buttonsGalore" method=" get" >
< fieldset style=" margin: 1em text-align: center " >
< legend> Select a Hero< /legend> < input type=" button" value=" Agamemnon" onclick=" displayHero(this)" />
< input type=" button" value=" Achilles" onclick=" displayHero(this)" /> < input type=" button" value=" Hector" onclick=" displayHero(this)" />
< div style=" height: 1em " /> 

13 :: Where are cookies actually stored on the hard disk? 
This depends on the user's browser and OS. In the case of Netscape with Windows OS, all the cookies are stored in a single file called cookies.txt c:Program FilesNetscapeUsersusernamecookies.txt In the case of IE,each cookie is stored in a separate file namely username@website.txt. c:WindowsCookiesusername@Website.txt 

14 :: What can JavaScript programs do? 
Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling 

15 :: How to set a HTML document's background color? 
document.bgcolor property can be set to any appropriate color. 

16 :: How can JavaScript be used to personalize or tailor a Web site to fit individual users? 
JavaScript allows a Web page to perform "if-then" kinds of decisions based on browser version, operating system, user input, and, in more recent browsers, details about the screen size in which the browser is running. While a server CGI program can make some of those same kinds of decisions, not everyone has access to or the expertise to create CGI programs. For example, an experienced CGI programmer can examine information about the browser whenever a request for a page is made thus a server so equipped might serve up one page for Navigator users and a different page for Internet Explorer users. Beyond browser and operating system version, a CGI program can't know more about the environment. But a JavaScript-enhanced page can instruct the browser to render only certain content based on the browser, operating system, and even the screen size. Scripting can even go further if the page author desires. For example, the author may include a preference screen that lets the user determine the desired background and text color combination. A script can save this information on the client in a well-regulated local file called a cookie. The next time the user comes to the site, scripts in its pages look to the cookie info and render the page in the color combination selected previously. The server is none the wiser, nor does it have to store any visitor-specific information. 

17 :: How is JavaScript different from Java? 
JavaScript was developed by Brendan Eich of Netscape Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements. JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the "Java" name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don't rely on each other and are intended for different purposes. In some ways, the "Java" name on JavaScript has confused the world's understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it. 

18 :: How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site? 
JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content. 

19 :: How can JavaScript be used to improve the "look and feel" of a Web site? 
By the same token, how can JavaScript be used to improve the user interface? On their own, Web pages tend to be lifeless and flat unless you add animated images or more bandwidth-intensive content such as Java applets or other content requiring plug-ins to operate (Shockwave and Flash, for example). Embedding JavaScript into an HTML page can bring the page to life in any number of ways. Perhaps the most visible features built into pages recently with the help of JavaScript are the so-called image rollovers: roll the cursor atop a graphic image and its appearance changes to a highlighted version as a feedback mechanism to let you know precisely what you're about to click on. But there are less visible yet more powerful enhancements to pages that JavaScript offers. Interactive forms validation is an extremely useful application of JavaScript. While a user is entering data into form fields, scripts can examine the validity of the data--did the user type any letters into a phone number field?, for instance. Without scripting, the user has to submit the form and let a server program (CGI) check the field entry and then report back to the user. This is usually done in a batch mode (the entire form at once), and the extra transactions take a lot of time and server processing power. Interactive validation scripts can check each form field immediately after the user has entered the data, while the information is fresh in the mind. 

20 :: Are you concerned that older browsers don't support JavaScript and thus exclude a set of Web users? individual users? 
Fragmentation of the installed base of browsers will only get worse. By definition, it can never improve unless absolutely everyone on the planet threw away their old browsers and upgraded to the latest gee-whiz versions. But even then, there are plenty of discrepancies between the script ability of the latest Netscape Navigator and Microsoft Internet Explorer. The situation makes scripting a challenge, especially for newcomers who may not be aware of the limitations of earlier browsers. A lot of effort in my books and ancillary material goes toward helping scripter know what features work in which browsers and how to either workaround limitations in earlier browsers or raise the compatibility common denominator. Designing scripts for a Web site requires making some hard decisions about if, when, and how to implement the advantages scripting offers a page to your audience. For public Web sites, I recommend using scripting in an additive way: let sufficient content stand on its own, but let scriptable browser users receive an enhanced experience, preferably with the same HTML document. 

21 :: What does isNaN function do? 
Return true if the argument is not a number. 

22 :: What is negative infinity? 
It’s a number in JavaScript, derived by dividing negative number by zero. 

23 :: In a pop-up browser window, how do you refer to the main browser window that opened it? 
Use window.opener to refer to the main window from pop-ups. 

24 :: What is the data type of variables of in JavaScript? 
All variables are of object type in JavaScript. 

25 :: Methods GET and POST in HTML forms - what's the difference? 
GET: Parameters are passed in the query string. Maximum amount of data that can be sent via the GET method is limited to about 2kb. POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair. 

 26 :: How to write a script for "Select" lists using JavaScript? 
1. To remove an item from a list set it to null mySelectObject.options[3] = null 2. To truncate a list set its length to the maximum size you desire mySelectObject.length = 2 3. To delete all options in a select object set the length to 0. mySelectObject.leng 

27 :: Text From Your Clipboard? 
It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server 

28 :: What does the "Access is Denied" IE error mean?
The "Access Denied" error in any browser is due to the following reason. A JavaScript in one window or frame is tries to access another window or frame whose document's domain is different from the document containing the script. 

29 :: Is a JavaScript script faster than an ASP script? 
Yes. Since JavaScript is a client-side script it does require the web server's help for its computation, so it is always faster than any server-side script like ASP, PHP, etc.. 

30 :: Are Java and JavaScript the Same? 
No. java and JavaScript are two different languages. Java is a powerful object - oriented programming language like C++, C whereas JavaScript is a client-side scripting language with some limitations. 

31 :: How to embed JavaScript in a web page? 
JavaScript code can be embedded in a web page between tags 

32 :: What and where are the best JavaScript resources on the Web? 
The Web has several FAQ areas on JavaScript. The best place to start is something called the meta-FAQ [14-Jan-2001 Editor's Note: I can't point to it anymore, it is broken!], which provides a high-level overview of the JavaScript help available on the Net. As for fact-filled FAQs, I recommend one maintained by Martin Webb and a mini-FAQ that I maintain. For interactive help with specific problems, nothing beats the primary JavaScript Usenet newsgroup, comp.lang.javascript. Depending on my work backlog, I answer questions posted there from time to time. Netscape and Microsoft also have vendor-specific developer discussion groups as well as detailed documentation for the scripting and object model implementations. 

33 :: What are the problems associated with using JavaScript, and are there JavaScript techniques that you discourage?
Browser version incompatibility is the biggest problem. It requires knowing how each scriptable browser version implements its object model. You see, the incompatibility rarely has to do with the core JavaScript language (although there have been improvements to the language over time); the bulk of incompatibility issues have to do with the object models that each browser version implements. For example, scripter who started out with Navigator 3 implemented the image rollover because it looked cool. But they were dismayed to find out that the image object wasn't scriptable in Internet Explorer 3 or Navigator 2. While there are easy workarounds to make this feature work on newer browsers without disturbing older ones, it was a painful learning experience for many. The second biggest can of worms is scripting connections between multiple windows. A lot of scripter like to have little windows pop up with navigation bars or some such gizmos. But the object models, especially in the older browser versions, don't make it easy to work with these windows the minute you put a user in front of them--users who can manually close windows or change their stacking order. More recently, a glitch in some uninstall routines for Windows 95 applications can disturb vital parts of the system Registry that Internet Explorer 4 requires for managing multiple windows. A scripter can't work around this problem, because it's not possible to detect the problem in a us 

34 :: What Boolean operators does JavaScript support? 
Boolean operators in JavaScript are as under &&, || and ! 

35 :: What does "1"+2+4 evaluate to?
Since 1 is a string, everything is a string, so the result is 124. 

36 :: What are the ways to emit client-side JavaScript from server-side code in ASP. NET? 
The Page object in ASP. NET has two methods that allow emitting of client-side JavaScript: RegisterClientScriptBlock and RegisterStartupScript. Example usage: Page.RegisterClientScriptBlock("ScriptKey", ""); Page.RegisterStartupScript("ScriptKey", ""); ScriptKey is used to suppress the same JavaScript from being emitted more than once. Multiple calls to RegisterClientScriptBlock or RegisterStartupScript with the same value of ScriptKey emit the script only once, on the first call. 

37 :: What is the difference between RegisterClientScriptBlock and RegisterStartupScript? RegisterClientScriptBlock emits the JavaScript just after the opening tag. RegisterStartupScript emits the JavaScript at the bottom of the ASP. NET page just before the closing tag. 

38 :: What is the difference between a web-garden and a web-farm? 
Web-garden - An IIS6.0 feature where you can configure an application pool as a web-garden and also specify the number of worker processes for that pool. It can help improve performance in some cases. Web-farm - a general term referring to a cluster of physically separate machines, each running a web-server for scalability and performance (contrast this with web-garden which refers to multiple processes on one single physical machine). 

39 :: How to get the contents of an input box using JavaScript? 
Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value; 

40 :: How to determine the state of a checkbox using JavaScript?
Determining the state of a checkbox in
JavaScript var checkedP = window.document.getElementById("myCheckBox").checked; 

41 :: How to set the focus in an element using Javascript? 
Setting the focus in an element using JavaScript 

42 :: How to access an external JavaScript file that is stored externally and not embedded? 
This can be achieved by using the following tag between head tags or between body tags. How to access an external JavaScript file that is stored externally and not embedded? where abc.js is the external JavaScript file to be accessed. 

43 :: What is the difference between an alert box and a confirmation box? 
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel. 

44 :: What is a prompt box? 
A prompt box allows the user to enter input by providing a text box.

45 :: Can JavaScript code be broken in different lines?
Breaking is possible within a string statement by using a backslash at the end but not within any other javascript statement. that is , document.write("Hello world"); is possible but not document.write ("hello world"); 

46 :: Taking a developer’s perspective, do you think that that JavaScript is easy to learn and use? 
One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs. The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely represent physical things you can see on a page: a text box, an image, and so on. It's easier to say, "OK, these are the things I'm working with and I'll use scripting to make them do such and such," instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code. 

47 :: What Web sites do you feel use JavaScript most effectively (i.e., best-in-class examples)? The worst?
The best sites are the ones that use JavaScript so transparently, that I'm not aware that there is any scripting on the page. The worst sites are those that try to impress me with how much scripting is on the page. 

48 :: How about 2+5+"8"? 
Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result. 

49 :: What is the difference between SessionState and ViewState? 
ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application. 

50 :: What does the EnableViewStateMac setting in an aspx page do? 
Setting EnableViewStateMac=true is a security measure that allows ASP. NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP. NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error - Validation of viewstate MAC failed. Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.

Thursday, October 13, 2011

History of PHP and related projects


Table of Contents

PHP has come a long way in the last few years. Growing to be one of the most prominent languages powering the Web was not an easy task. Those of you interested in briefly seeing how PHP grew out to what it is today, read on. Old PHP releases can be found at the » PHP Museum.

History of PHP

PHP/FI

PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995, initially as a simple set of Perl scripts for tracking accesses to his online resume. He named this set of scripts 'Personal Home Page Tools'. As more functionality was required, Rasmus wrote a much larger C implementation, which was able to communicate with databases, and enabled users to develop simple dynamic Web applications. Rasmus chose to » release the source code for PHP/FI for everybody to see, so that anybody can use it, as well as fix bugs in it and improve the code. PHP/FI, which stood for Personal Home Page / Forms Interpreter, included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent. By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project. PHP/FI 2.0 was officially released only in November 1997, after spending most of its life in beta releases. It was shortly afterwards succeeded by the first alphas of PHP 3.0.

PHP 3

PHP 3.0 was the first version that closely resembles PHP as we know it today. It was created by Andi Gutmans and Zeev Suraski in 1997 as a complete rewrite, after they found PHP/FI 2.0 severely underpowered for developing an eCommerce application they were working on for a University project. In an effort to cooperate and start building upon PHP/FI's existing user-base, Andi, Rasmus and Zeev decided to cooperate and announce PHP 3.0 as the official successor of PHP/FI 2.0, and development of PHP/FI 2.0 was mostly halted. One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a solid infrastructure for lots of different databases, protocols and APIs, PHP 3.0's extensibility features attracted dozens of developers to join in and submit new extension modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 were the object oriented syntax support and the much more powerful and consistent language syntax. The whole new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was named plain 'PHP', with the meaning being a recursive acronym - PHP: Hypertext Preprocessor. By the end of 1998, PHP grew to an install base of tens of thousands of users (estimated) and hundreds of thousands of Web sites reporting it installed. At its peak, PHP 3.0 was installed on approximately 10% of the Web servers on the Internet. PHP 3.0 was officially released in June 1998, after having spent about 9 months in public testing.

PHP 4

By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently. The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor, PHP 3.0. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more Web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs. Today, PHP is being used by hundreds of thousands of developers (estimated), and several million sites report as having it installed, which accounts for over 20% of the domains on the Internet. PHP's development team includes dozens of developers, as well as dozens others working on PHP-related projects such as PEAR and the documentation project.

PHP 5

PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features.

The History of PHP

PHP is an "HTML-embedded scripting language" primarily used for dynamic Web applications. The first part of this definition means that PHP code can be interspersed with HTML, making it simple to generate dynamic pieces of Web pages on the fly. As a scripting language, PHP code requires the presence of the PHP processor. PHP code is normally run in plain-text scripts that will only run on PHP-enabled computers (conversely programming languages can create standalone binary executable files, a.k.a. programs). PHP takes most of its syntax from C, Java, and Perl. It is an open source technology and runs on most operating systems and with most Web servers. PHP was written in the C programming language by Rasmus Lerdorf in 1994 for use in monitoring his online resume and related personal information. For this reason, PHP originally stood for "Personal Home Page". Lerdorf combined PHP with his own Form Interpreter, releasing the combination publicly as PHP/FI (generally referred to as PHP 2.0) on June 8, 1995. Two programmers, Zeev Suraski and Andi Gutmans, rebuilt PHP's core, releasing the updated result as PHP/FI 2 in 1997. The acronym was formally changed to PHP: HyperText Preprocessor, at this time. (This is an example of a recursive acronym: where the acronym itself is in its own definition.) In 1998, PHP 3 was released, which was the first widely used version. PHP 4 was released in May 2000, with a new core, known as the Zend Engine 1.0. PHP 4 featured improved speed and reliability over PHP 3. In terms of features, PHP 4 added references, the Boolean type, COM support on Windows, output buffering, many new array functions, expanded object-oriented programming, inclusion of the PCRE library, and more. Maintenance releases of PHP 4 are still available, primarily for security updates. PHP 5 was released in July 2004, with the updated Zend Engine 2.0. Among the many new features in PHP 5 are: and much, much more. PHP 6 has been in development since October of 2006. The most significant change will be native support for Unicode. Unpopular, deprecated features such as Magic Quotes, register_globals, safe_mode, and the HTTP_*_VARS variables will disappear in PHP 6. Although PHP is still primarily used for server-side generation of Web pages, it can also be used to perform command-line scripting or to create graphical applications with the help of GTK+. [[We should add some discussion of the history of NuSphere and PhpED here but I couldn't find anything that specific on your site.]]

Wednesday, October 12, 2011

Advanced PHP: php oops

Advanced PHP: php oops: Introduction Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major chan...

Sunday, October 9, 2011

100 PHP Interview Questions and Answers

100 PHP interview questions and answers are below.
Questions  : 1 Who is the father of PHP ?
Answers : 1 Rasmus Lerdorf is known as the father of PHP.
Questions : 2 What is the difference between $name and $$name?
Answers : 2 $name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia value is singh.
Questions : 3 How can we submit a form without a submit button?
Answer : 3 Java script submit() function is used for submit form without submit button on click call document.formname.submit()
Questions : 4 In how many ways we can retrieve the data in the result set of MySQL using PHP?
Answer : 4 We can do it by 4 Ways 1. mysql_fetch_row. , 2. mysql_fetch_array , 3. mysql_fetch_object 4. mysql_fetch_assoc
Questions : 5 What is the difference between mysql_fetch_object and mysql_fetch_array?
Answers : 5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Questions : 6 What are the differences between Get and post methods.
Answers : 6 There are some defference between GET and POST method 1. GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send 2. when we use GET method requested data show in url but Not in POST method so POST method is good for send sensetive request
Questions : 7 How can we extract string "pcds.co.in " from a string "http://info@pcds.co.in using regular expression of PHP?
Answers : 7 preg_match("/^http:\/\/.+@(.+)$/","http://info@pcds.co.in",$matches); echo $matches[1];
Questions : 8 How can we create a database using PHP and MySQL?
Answers : 8 We can create MySQL database with the use of mysql_create_db("Database Name")
Questions : 9 What are the differences between require and include?
Answers : 9 Both include and require used to include a file but when included file not found Include send Warning where as Require send Fatal Error .
Questions : 10 Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"?
Answers : 10 Yes we can use include("xyz.php") more than one time in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob
Questions : 11 What are the different tables(Engine) present in MySQL, which one is default?
Answers : 11 Following tables (Storage Engine) we can create 1. MyISAM(The default storage engine IN MYSQL Each MyISAM table is stored on disk in three files. The files have names that begin with 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) extension. The index file has an .MYI (MYIndex) extension. ) 2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.) 3. Merge 4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for backward compatibility. ) 5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions) 6. EXAMPLE 7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. ) 8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. ) 9. CSV (The CSV storage engine stores data in text files using comma-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)
Questions : 12 What is use of header() function in php ?
Answers : 12 The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is seen..
Questions : 13 How can I execute a PHP script using command line?
Answers : 13 Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument.
Questions : 14 Suppose your Zend engine supports the mode <? ?> Then how can u configure your PHP Zend engine to support <?PHP ?> mode ?
Answers : 14 In php.ini file: set short_open_tag=on to make PHP support
Questions : 15 Shopping cart online validation i.e. how can we configure Paypal, etc.?
Answers : 15 Nothing more we have to do only redirect to the payPal url after submit all information needed by paypal like amount,adresss etc.
Questions : 16 What is meant by nl2br()?
Answers : 16 Inserts HTML line breaks (<BR />) before all newlines in a string.
Questions : 17 What is htaccess? Why do we use this and Where?
Answers : 17 .htaccess files are configuration files of Apache Server which provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
Questions : 18 How we get IP address of client, previous reference page etc ?
Answers : 18 By using $_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER'] etc.
Questions : 19 What are the reasons for selecting lamp (Linux, apache, MySQL, PHP) instead of combination of other software programs, servers and operating systems?
Answers : 19 All of those are open source resource. Security of Linux is very very more than windows. Apache is a better server that IIS both in functionality and security. MySQL is world most popular open source database. PHP is more faster that asp or any other scripting language.
Questions : 20 How can we encrypt and decrypt a data present in a MySQL table using MySQL?
Answers : 20 AES_ENCRYPT () and AES_DECRYPT ()
Questions : 21 How can we encrypt the username and password using PHP?
Answers : 21 The functions in this section perform encryption and decryption, and compression and uncompression:
encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()
Questions : 22 What are the features and advantages of object-oriented programming?
Answers : 22 One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system
Questions : 23 What are the differences between procedure-oriented languages and object-oriented languages?
Answers : 23 There are lot of difference between procedure language and object oriented like below 1>Procedure language easy for new developer but complex to understand whole software as compare to object oriented model 2>In Procedure language it is difficult to use design pattern mvc , Singleton pattern etc but in OOP you we able to develop design pattern 3>IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE .
Questions : 24 What is the use of friend function?
Answers : 24 Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class. A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.
Questions : 25 What are the differences between public, private, protected, static, transient, final and volatile?
Answer : 25 Public: Public declared items can be accessed everywhere. Protected: Protected limits access to inherited and parent classes (and to the class that defines the item). Private: Private limits visibility only to the class that defines the item. Static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Final: Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. transient: A transient variable is a variable that may not be serialized. volatile: a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.
Questions : 26 What are the different types of errors in PHP?
Answer : 26 Three are three types of errors:1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although, as you will see, you can change this default behavior.2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed 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 a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.
Questions : 27 What is the functionality of the function strstr and stristr?
Answers : 27 strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string. $email= 'sonialouder@gmail.com'; $domain = strstr($email, '@'); echo $domain; // prints @gmail.com here @ is the needle stristr is case-insensitive means able not able to diffrenciate between a and A
Questions : 28 What are the differences between PHP 3 and PHP 4 and PHP 5?
Answer : 28 There are lot of difference among these three version of php 1>Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6 have to come 2>Difference mean oldest version have less functionality as compare to new one like php5 have all OOPs concept now where as php3 was pure procedural language constructive like C In PHP5 1. Implementation of exceptions and exception handling 2. Type hinting which allows you to force the type of a specific argument 3. Overloading of methods through the __call function 4. Full constructors and destructors etc through a __constuctor and __destructor function 5. __autoload function for dynamically including certain include files depending on the class you are trying to create. 6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all. 7 Interfaces & Abstract Classes 8 Passed by Reference : 9 An __clone method if you really want to duplicate an object
Questions : 29 How can we convert asp pages to PHP pages?
Answer : 29 there are lots of tools available for asp to PHP conversion. you can search Google for that. the best one is available athttp://asp2php.naken.cc./
Questions : 30 What is the functionality of the function htmlentities?
Answer : 30 Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
Questions : 31 How can we get second of the current time using date function?
Answer : 31 $second = date("s");
Questions : 32 How can we convert the time zones using PHP?
Answer : 32 By using date_default_timezone_get and date_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: date_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/Eastern date_default_timezone_set('US/Eastern'); // Output the date in a standard format (RFC1123), this will print: // Fri, 31 Dec 1999 18:00:00 EST echo '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>
Questions : 33 What is meant by urlencode and urldocode?
Answer : 33 URLencode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type.urldecode decodes any %## encoding in the given string.
Questions : 34 What is the difference between the functions unlink and unset?
Answer : 34 unlink() deletes the given file from the file system. unset() makes a variable undefined.
Questions : 35 How can we register the variables into a session?
Answer : 35 $_SESSION['name'] = "sonia";
Questions : 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 () function To know the Image size use getimagesize () function To know the image width use imagesx () function To know the image height use imagesy() function t
Questions : 37 How can we get the browser properties using PHP?
Answer : 37 By using $_SERVER['HTTP_USER_AGENT'] variable.
Questions : 38 What is the maximum size of a file that can be uploaded using PHP and how can we change this?
Answer : 38 By default the maximum size is 2MB. and we can change the following setup at php.iniupload_max_filesize = 2M
Questions : 39 How can we increase the execution time of a PHP script?
Answer : 39 by changing the following setup at php.inimax_execution_time = 30 ; Maximum execution time of each script, in seconds
Questions : 40 How can we take a backup of a MySQL table and how can we restore it. ?
Answer : 40 To backup: BACKUP TABLE tbl_name[,tbl_name…] TO '/path/to/backup/directory' RESTORE TABLE tbl_name[,tbl_name…] FROM '/path/to/backup/directory'mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table. -t, –no-create-info Don't write table creation information (the CREATE TABLE statement). -d, –no-data Don't write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!
Questions : 41 How can we optimize or increase the speed of a MySQL select query?
Answer : 41
  • first of all instead of using select * from table1, use select column1, column2, column3.. from table1
  • Look for the opportunity to introduce index in the table you are querying.
  • use limit keyword if you are looking for any specific number of rows from the result set.
Questions : 42 How many ways can we get the value of current session id?
Answer : 42 session_id() returns the session id for the current session.
Questions : 43 How can we destroy the session, how can we unset the variable of a session?
Answer : 43 session_unregister — Unregister a global variable from the current session session_unset — Free all session variables
Questions : 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. like setcookie("user", "sonia", time()+3600); for set the cookie setcookie("user", "", time()-3600); for destroy or delete the cookies;
Questions : 45 How many ways we can pass the variable through the navigation between the pages?
Answer : 45
  • GET/QueryString
  • POST
Questions : 46 What is the difference between ereg_replace() and eregi_replace()?
Answer : 46 eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.
Questions : 47 What are the different functions in sorting an array?
Answer : 47 Sort(), arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort(), and uksort().
Questions : 48 How can we know the count/number of elements of an array?
Answer : 48 2 ways a) sizeof($urarray) This function is an alias of count() b) count($urarray)
Questions : 49 what is session_set_save_handler in PHP?
Answer : 49 session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.
Questions : 50 How can I know that a variable is a number or not using a JavaScript?
Answer : 50 bool is_numeric ( mixed var) Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.
Questions : 51 List out some tools through which we can draw E-R diagrams for mysql.
Answer : 51 Case Studio Smart Draw
Questions : 52 How can I retrieve values from one database server and store them in other database server using PHP?
Answer : 52 we can always fetch from one database and rewrite to another. here is 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 fetch records from you previous ResultSet, i.e $res1 – But you cannot execute new query in $db1, even if you supply the link as because the link was overwritten by the new db.so at this point the following script will fail $res3 = mysql_query("query",$db1); //this will failSo how to solve that?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 which indicates whether a link will be created or not. as we connect to the $db2 with this optional parameter set to 'true', so both link will remain live. now the following query will execute successfully. $res3 = mysql_query("query",$db1);
Questions : 53 List out the predefined classes in PHP?
Answer : 53 Directory stdClass __PHP_Incomplete_Class exception php_user_filter
Questions : 54 How can I make a script that can be bi-language (supports English, German)?
Answer : 54 You can maintain two separate language file for each of the language. all the labels are putted in both language files as variables and assign those variables in the PHP source. on runtime choose the required language option.
Questions : 55 What are the difference between abstract class and interface?
Answer : 55 Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class.
Questions : 56 How can we send mail using JavaScript?
Answer : 56 JavaScript does not have any networking capabilities as it is designed to work on client site. As a result we can not send mails using JavaScript. But we can call the client side mail protocol mailto via JavaScript to prompt for an email to send. this requires the client to approve it.
Questions : 57 How can we repair a MySQL table?
Answer : 57 The syntex for repairing a MySQL table is REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended] This command will repair the table specified if the quick is given the MySQL will do a repair of only the index tree if the extended is given it will create index row by row
Questions : 58 What are the advantages of stored procedures, triggers, indexes?
Answer : 58 A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.
Questions : 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 for each type of identifier.
Identifier Maximum Length (bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255
There are some restrictions on the characters that may appear in identifiers:
Questions : 60 How many values can the SET function of MySQL take?
Answer : 60 MySQL set can take zero or more values but at the maximum it can take 64 values
Questions : 61 What are the other commands to know the structure of table using MySQL commands except explain command?
Answer : 61 describe Table-Name;
Questions : 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,
Questions : 63 What is the purpose of the following files having extensions 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 have names that begin with the table name and have an extension to indicate the file type. The '.frm' file stores the table definition. The data file has a '.MYD' (MYData) extension. The index file has a '.MYI' (MYIndex) extension,
Questions : 64 What is maximum size of a database in MySQL?
Answer : 64 If the operating system or filesystem places a limit on the number of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, database performance can be adversely affected. The amount of available disk space limits the number of tables. MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 – 1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB. The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation specific to your operating system. Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB) Linux 2.4+ (using ext3 filesystem) 4TB Solaris 9/10 16TB NetWare w/NSS filesystem 8TB Win32 w/ FAT/FAT32 2GB/4GB Win32 w/ NTFS 2TB (possibly larger) MacOS X w/ HFS+ 2TB
Questions : 65 Give the syntax of Grant and Revoke commands?
Answer : 65 The generic syntax for grant is as following > GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY [password] now rights can be a) All privileges b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all databse by using *.* or some specific database by database.* or a specific table by database.table_name username@hotsname can be either username@localhost, username@hostname and username@% where hostname is any valid hostname and % represents any name, the *.* any condition password is simply the password of userThe generic syntax for revoke is as following > REVOKE [rights] on [database/s] FROM [username@hostname] now rights can be as explained above a) All privileges b) combination of create, drop, select, insert, update and delete etc. username@hotsname can be either username@localhost, username@hostname and username@% where hostname is any valid hostname and % represents any name, the *.* any condition
Questions : 66 Explain Normalization concept?
Answer : 66 The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).Second Normal FormWhere the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.Third Normal FormI have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table
Questions : 67 How can we find the number of rows in a table using MySQL?
Answer : 67 Use this for mysql >SELECT COUNT(*) FROM table_name;
Questions : 68 How can we find the number of rows in a result set using PHP?
Answer : 68 $result = mysql_query($sql, $db_link); $num_rows = mysql_num_rows($result); echo "$num_rows rows found";
Questions : 69 How many ways we can we find the current date using MySQL?
Answer : 69 SELECT CURDATE(); CURRENT_DATE() = CURDATE() for time use SELECT CURTIME(); CURRENT_TIME() = CURTIME()
Questions : 70 What are the advantages and disadvantages of Cascading Style Sheets?
Answer : 70 External Style SheetsAdvantagesCan control styles for multiple documents at once. Classes can be created for use on multiple HTML element types in many documents. Selector and grouping methods can be used to apply styles under complex contextsDisadvantagesAn extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of style definitionsEmbedded Style SheetsAdvantagesClasses can be created for use on multiple tag types in the document. Selector and grouping methods can be used to apply styles under complex contexts. No additional downloads necessary to receive style informationDisadvantages This method can not control styles for multiple documents at once Inline Styles Advantages Useful for small quantities of style definitions. Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods Disadvantages Does not distance style information from content (a main goal of SGML/HTML). Can not control styles for multiple documents at once. Author can not create or control classes of elements to control multiple element types within the document. Selector grouping methods can not be used to create complex element addressing scenarios
Questions : 71 What type of inheritance that PHP supports?
Answer : 71 In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'.
Questions : 72 What is the difference between Primary Key and Unique key?
Answer : 72 Primary Key: A column in a table whose values uniquely identify the rows in the table. A primary key value cannot be NULL.Unique Key: Unique Keys are used to uniquely identify each row in the table. There can be one and only one row for each unique key value. So NULL can be a unique key.There can be only one primary key for a table but there can be more than one unique for a table.
Question : 73 what is garbage collection? default time ? refresh time?
Answer : 73 Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. Garbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, 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 or 24 minutes session.gc_probability 1 session.gc_divisor 100
Questions : 74 What are the advantages/disadvantages of MySQL and PHP?
Answer : 74 Both of them are open source software (so free of cost), support cross platform. php is faster then ASP and JSP.
Questions : 75 What is the difference between GROUP BY and ORDER BY in Sql?
Answer : 75 ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.GROUP BY [col1],[col2],…,[coln]; Tels DBMS to group results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average
Questions : 76 What is the difference between char and varchar data types?
Answer : 76 Set char to occupy n bytes and it will take n bytes even if u r storing a value of n-m bytes Set varchar to occupy n bytes and it will take only the required space and will not use the n bytes eg. name char(15) will waste 10 bytes if we store 'romharshan', if each char takes a byte eg. name varchar(15) will just use 5 bytes if we store 'romharshan', if each char takes a byte. rest 10 bytes will be free.
Questions : 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 to identify users etc. If I add random no techniques to it the md5 generated now will be totally different for the same string I am using.
Questions : 78 How can I load data from a text file into a table?
Answer : 78 you can use LOAD DATA INFILE file_name; syntax to load data from a text file. but you have to make sure thata) data is delimited b) columns and data matched correctly
Questions : 79 How can we know the number of days between two given dates using MySQL?
Answer : 79 SELECT DATEDIFF("2007-03-07","2005-01-01");
Questions : 80 How can we know the number of days between two given dates using PHP?
Answer : 80 $date1 = date("Y-m-d"); $date2 = "2006-08-15"; $days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);
Questions : 81 How we load all classes that placed in different directory in one PHP File , means how to do auto load classes
Answer : 81 by using spl_autoload_register('autoloader::function'); Like below class 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');
Questions : 82 How many types of Inheritances used in PHP and how we achieve it
Answer : 82 As far PHP concern it only support single Inheritance in scripting. we can also use interface to achieve multiple inheritance.
Questions : 83 PHP how to know user has read the email?
Answers : 83 Using Disposition-Notification-To: in mailheader we can get read receipt. Add the possibility to define a read receipt when sending an email. It’s quite straightforward, just edit email.php, and add this at vars definitions: var $readReceipt = null; And then, at ‘createHeader’ function add: if (!empty($this->readReceipt)) { $this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine; }
Questions : 84 What are default session time and path?
Answers : 84 default session time in PHP is 1440 seconds or 24 minutes Default session save path id temporary folder /tmp
Questions : 85 how to track user logged out or not? when user is idle ?
Answers : 85 By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes. The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.
Questions : 86 how to track no of user logged in ?
Answers : 86 whenever a user logs in track the IP, userID etc..and store it in a DB with a active flag while log out or sesion expire make it inactive. At any time by counting the no: of active records we can get the no: of visitors.
Questions : 87 in PHP for pdf which library used?
Answers : 87 The PDF functions in PHP can create PDF files using the PDFlib library With version 6, PDFlib offers an object-oriented API for PHP 5 in addition to the function-oriented API for PHP 4. There is also the » Panda module. FPDF is a PHP class which allows to generate PDF files with pure PHP, that is to say without using the PDFlib library. F from FPDF stands for Free: you may use it for any kind of usage and modify it to suit your needs. FPDF requires no extension (except zlib to activate compression and GD for GIF support) and works with PHP4 and PHP5.
Questions : 88 for image work which library?
Answers : 88 we will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.
Questions : 89 what is design pattern? singleton pattern?
Answers : 89 A design pattern is a general reusable solution to a commonly occurring problem in software design. The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.
Questions : 90 what are magic methods?
Answers : 90 Magic methods are the members functions that is available to all the instance of class Magic methods always starts with "__". Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct() __destruct() __set() __get() __call() __toString() __sleep() __wakeup() __isset() __unset() __autoload() __clone()
Questions : 91 what is magic quotes?
Answers : 91 Magic Quotes is a process that automagically escapes ncoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed. This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.
Questions : 92 what is cross site scripting? SQL injection?
Answers : 92 Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts. SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed
Questions : 93 what is URL rewriting?
Answers : 93 Using URL rewriting we can convert dynamic URl to static URL Static URLs are known to be better than Dynamic URLs because of a number of reasons 1. Static URLs typically Rank better in Search Engines. 2. Search Engines are known to index the content of dynamic pages a lot slower compared to static pages. 3. Static URLs are always more friendlier looking to the End Users. along with this we can use URL rewriting in adding variables [cookies] to the URL to handle the sessions.
Questions : 94 what is the major php security hole? how to avoid?
Answers : 94 1. Never include, require, or otherwise open a file with a filename 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 the malicious user the ability to execute any command he or she wishes! 3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes 4. Never run unescaped queries 5. For protected areas, use sessions or validate the login every time. 6. If you don’t want the file contents to be seen, give the file a .php extension.
Questions : 95 whether PHP supports Microsoft SQL server ?
Answers : 95 The SQL Server Driver for PHP v1.0 is designed to enable reliable, scalable integration with SQL Server for PHP applications deployed on the Windows platform. The Driver for PHP is a PHP 5 extension that allows the reading and writing of SQL Server data from within PHP scripts. using MSSQL or ODBC modules we can access Microsoft SQL server.
Questions : 96 what is MVC? why its been used?
Answers : 96 Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model. WHY ITS NEEDED IS 1 Modular separation of function 2 Easier to maintain 3 View-Controller separation means: A — Tweaking design (HTML) without altering code B — Web design staff can modify UI without understanding code
Questions : 97 what is framework? how it works? what is advantage?
Answers : 97 In general, a framework is a real or conceptual structure intended to serve as a support or guide for the building of something that expands the structure into something useful. Advantages : Consistent Programming Model Direct Support for Security Simplified Development Efforts Easy Application Deployment and Maintenance
Questions : 98 what is CURL?
Answers : 98 CURL means Client URL Library curl is a command line tool for transferring files with URL syntax, supporting 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, kerberos…), file transfer resume, proxy tunneling and a busload of other useful tricks. CURL allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
Questions : 99 what is PDO ?
Answers : 99 The PDO ( PHP Data Objects ) extension defines a lightweight, consistent interface for accessing databases in PHP. if you are using the PDO API, you could switch the database server you used, from say PgSQL to MySQL, and only need to make minor changes to your PHP code.While PDO has its advantages, such as a clean, simple, portable API but its main disadvantage is that it doesn't allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL's support for Multiple Statements. Just need to use below code for connect mysql using PDO try { $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) { echo $e->getMessage(); }
Questions : 100 What is PHP's mysqli Extension?
Answers : 100 The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.The mysqli extension has a number of benefits, the key enhancements over the mysql extension being: =>Object-oriented interface =>Support for Prepared Statements =>Support for Multiple Statements =>Support for Transactions =>Enhanced debugging capabilities =>Embedded server support