Академический Документы
Профессиональный Документы
Культура Документы
In the get method the data made available to the action page ( where data is received ) by
the URL so data can be seen in the address bar. Not advisable if you are sending login
info like password etc.In the post method the data will be available as data blocks and not
as query string.
MySQL fetch object will collect first single matching record where mysql_fetch_array
will collect all matching records from the table in an array
Both are two variables. In the second case the value of the $message will be substituted
in the $message part and a new variable will create. i.e., $message is a simple variable
whereas $$message is a reference variable.
Example:
$user = 'bob' is equivalent to
$holder = 'user';
$$holder = 'bob';
Anwser 2:
They are both variables. But $message is a variable with a fixed name. $$message is a
variable who's name is stored in $message. For example, if $message contains "var",
$$message is the same as $var.
function myfunc($argument) {
echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
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'.
Explain different types of errors in php (i.e. arguments in error reporting function)?
nl2br — Inserts HTML line breaks before all newlines in a string string nl2br (string);
Returns string with ‘’ inserted before all newlines. For example: echo nl2br("god blessn
you") will output "god bless n you" to your browser.
How can we get second of the current time using date function?
$second = date("s");
How many ways can we get the value of current session id?
How can we destroy the session, how can we unset the variable of a session?
How many ways we can pass the variable through the navigation between the pages?
2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data
across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to
the session by a script can be retrieved by the same script or another script when
requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer
a complete functional transaction for the same visitor.
Answer1:
PEAR is the next revolution in PHP. This repository is bringing higher level
programming to PHP. PEAR is a framework and distribution system for reusable PHP
components. It eases installation by bringing an automated wizard, and packing the
strength and experience of PHP users into a nicely organised OOP library. PEAR also
provides a command-line interface that can be used to automatically install "packages"
Answer2:
PEAR is short for "PHP Extension and Application Repository" and is pronounced just
like the fruit. The purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body.
unlink() is a function for file system handling. It will simply delete the file in context.
unset() is a function for variable management. It will make a variable undefined.
htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand.
htmlentities translates all occurrences of character sequences that have different meaning
in HTML.
string md5(string)
It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.
setcookie('variable','value','time');
variable - name of the cookie variable
value - value of the cookie variable
time - expiry time
Example: setcookie('Test',$i,time()+3600);
Test - cookie variable name
$i - value of the variable 'Test'
time()+3600 - denotes that the cookie will expire after an one hour
__construct( )
Called when instantiating an object
__destruct( )
Called when deleting an object
Constructors and destructors are functions that are called when a new instance of an
object is created (constructors) and/or destroyed (destructors). Their primary purpose is to
allow for a means to initialize and clean up after an object during its use.Constructors can
accept parameters, which are assigned to specific object fields at creation time.
Constructors can call class methods or other functions.constructors are intuitively useful
for initializing class properties,Class constructors can call on other constructors,
including those from the class parent.One classic example is a class to access a database
back end, where a constructor could make the connection to the database while the
destructor closes it.
PHP 4 Constructors
In PHP 4, only constructors were available and were created by defining a function
whose name was the same as the class itself:
<?php
class MyClass {
function MyClass($param) {
echo "Created a new instance of MyClass !";
}
}
$Myinstance = new MyClass;
?>
In PHP 5, this concept has been changed PHP 5 or (5>=) now uses a unified constructor
function named __construct(). PHP 5 or (5>=) also uses a unified
__destruct() method for its destructors.
PHP 5 Constructors and Destructors
<?php
class MyClass {
function __construct($p) {
echo "Created a new instance of MyClass!";
}
function __destruct() {
echo "Destroyed this instance of MyClass";
}
}
$Myinstance = new MyClass("value");
?>
Encapsulation is the mechanism that binds together code and data it manipulates and
keeps both safe from out side interference and miss use .To implement this concept ,
PHP 5 supports public, private, and protected variables and member functions .
How many HTTP headers will send to a web page(client side) from server when you use
sessions (session_start()) in php ?
How to capture content from the output buffer ? or Give me an example for Output
caching in php?
<?php
ob_start(); // start an output buffer
echo ‘This text is from the codlib buffer*******<br />’; // output that will be stored in
the buffer
$codlib = ob_get_contents(); // store buffer content in $w3buffer variable
ob_end_clean(); // stop and clean the output buffer
echo ‘This is not from the codlib buffer!!!!!!!!<br />’;
echo $codlib;
?>
O/p
*****
This is not from the codlib buffer!!!!!!!!
This text is from the codlib buffer*******
<?php
$p = getcwd();
echo $p;
?>
When I try to connect to mysql from php I get this error: "Call to unsupported or
undefined function mysql_connect();"
Either you are missing mysql support in the php module or you need to load mysql
dynamicly in your scripts by inserting:
dl("mysql.so"); (on unix)
dl("mysql.dll"); (on windows);
in the top of all the scripts that use mysql.
But it is recomended to compile php with mysql.
How can I send variables from a PHP script to another URL using POST without using
forms and hidden variables?
You can open an HTTP socket connection and send HTTP POST commands. Here is
an example :
<?
// Generate the request header
$ReqHeader =
"POST $URI HTTP/1.1n".
"Host: $Hostn".
"Content-Type: application/x-www-form-urlencodedn".
"Content-Length: $ContentLengthnn".
"$ReqBodyn";
You just echo / print the javascript like you would do with html, like:
<?
echo "<script language="JavaScript">n";
echo "alert("javascript from php");n";
echo "</script>";
?>
How to count number of parameters given in URL by POST?
<?
echo count ($_POST);
?>
<?
$number = 15;
printf("%05d", $number);
?>
The quick answer is no, then you are probably asking why can't I do that with php. OK
here is a longer answer. PHP is a serverside scripting language and therefor has nothing
to do with the type of a specific client. Then you might ask "why can I then get the
browser agent from php?", thats because that information is sent with the initial HTTP
headers upon requst to the server. So if you want client information that's not sent with
the HTTP header you must a client scripting language like javascript.
You have not RTFM'ed good enough, if you read the man page for rand carefully you will
find a line that states:
"Remember to seed the random number generator before use with srand()."
So the proper code would be:
srand((double)microtime()*1000000);
$iRandom = rand(0,100);
As an alternative you can use mt_rand which should generate more random, numbers.
MYSQL
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,
How can we find the number of rows in a table using mysql?
How can we find the number of rows in a result set using php?
How many ways we can we find the current date using mysql?
SELECT CURDATE();
CURRENT_DATE() = CURDATE();
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME();
In both cases let the value for auto increment field be n then next row will have value n+1
i.e. 2346
In general, when you want to make a slow SELECT … WHERE query faster, the first
thing to check is whether you can add an index. All references between different tables
should usually be done with indexes. You can use the EXPLAIN statement to determine
which indexes are used for a SELECT.
To help MySQL optimize queries better, use ANALYZE TABLE or run myisamchk –
analyze on a table after it has been loaded with data. This updates a value for each index
part that indicates the average number of rows that have the same value. (For unique
indexes, this is always 1.) MySQL will use this to decide which index to choose when
you join two tables based on a non-constant expression. You can check the result from the
table analysis by using SHOW INDEX FROM tbl_name and examining the Cardinality
value. myisamchk –description –verbose shows index distribution information.
To sort an index and data according to an index, use myisamchk –sort-index –sort-
records=1 (if you want to sort on index 1). This is a good way to make queries faster if
you have a unique index from which you want to read all records in order according to
the index. Note that the first time you sort a large table this way, it may take a long time.
What is the maximum length of a table name, database name, and fieldname in mysql?
Database name- 64
Table name -64
Fieldname-64
What are the other commands to know the structure of table using mysql commands
except explain command?
describe table_name;
How many ways we can we find the current date using MySQL?
SELECT CURDATE();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();
How can we encrypt and decrypt a data present in a mysql table using mysql?
How can we know the number of days between two given dates using MySQL?
Use DATEDIFF()
SELECT DATEDIFF(NOW(),'2006-07-01');
DISTINCT
How would you select all the users, whose email address is null(empty)?
SELECT usrname FROM customers WHERE ISNULL(usremail);
What happens when the column is set to AUTO INCREMENT and we reach the
maximum valuen for that table?
It stops incrementing. It does not move to 0 to prevent data losses, but further inserts are
going to produce an error
SELECT SQL_NO_CACHE
include this (SQL_NO_CACHE) in select query while you retrieve the data from mysql
Adding a WITH ROLLUP modifier to the GROUP BY clause causes the query to
produce another row.
eg:
mysql> SELECT year, SUM(profit) FROM sales GROUP BY year WITH ROLLUP;
+------+-------------+
| year | SUM(profit) |
+------+-------------+
| 2000 | 4525 |
| 2001 | 3010 |
| NULL | 7535 | <<<- Note here*
+------+-------------+
So an extra row (<<<- Note here*) is created by mysql and also we get total profit
in the last column.
It Makes the MySQL engine refuse UPDATE and DELETE commands where the
WHERE clause is not present.
If you set the environment variable TZ=GB, then start MySQL the time zone will be set
to UK time.
I.E. (Linux only)
bash:#TZ=GB
bash:#export TZ
bash:#mysqld &
You can also set environment variables in my.cnf; In the data (normally var) directory.
errcode: 28
No space left on device
This means that you are out of disk space.
Try du to see how much space is free/used
JavaScript
What is JavaScript?
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
we can use javascript for submitting the form. Trigger the JavaScript code on any event
( like onselect of drop down list box, onfocus, etc )
document.myform.submit();
CSS
Stylesheets, as the name suggest, define styles (look and feel) for the content that HTML
holds. One can re-use same set of CSS styles over number of pages
throughout the website to keep a consistent look and feel. Stylesheets help web designers
keep the HTML clean and separate styles from the content.
One doesn't have to declare repeating styles for the child elements. E.g. if <body> has a
font-name style set to Arial, by default all the elements in the
HTML document will inherit this property, unless defined separately.
Using CLASS selectors in CSS one can assign style information to all elements. Class
selectors name in CSS is preceded by full stop.
The class selectors which can be applied multiple times to different element within a
page to format content.
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style
sheet by the following rules, where number four has the highest priority:
1. Browser default
2. External style sheet
3. Internal style sheet (inside the <head> tag)
4. Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it
will override a style declared inside the <head> tag, in an external style sheet, or in a
browser (a default value).
The at-rule in CSS begins with the at-keyword. It is then followed by '@' character and
then the identifier. Some of the at-rule in CSS are '@import', '@page'.
The "first-line" pseudo-element is used to add special styles to the first line of the text in
a selector:
p {font-size: 12pt}
p:first-line {color: #FF0000;font-variant:small-caps}
<p>Some text that ends up on two or more lines</p>
In the example above the browser displays the first line formatted according to the "first-
line" pseudo element. Where the browser breaks the line depends on the size of the
browser window.
Note: The "first-line" pseudo-element can only be used with block-level elements.
Note: The following properties apply to the "first-line" pseudo-element:
* font properties
* color properties
* background properties
* word-spacing
* letter-spacing
* text-decoration
* vertical-align
* text-transform
* line-height
* clear
Pseudo-elements can also be combined with CSS classes:
p.article:first-line {color: #FF0000}
<p class="article">A paragraph in an article</p>
The example above will set the first line of all paragraphs with class="article" to red.
what is selector?
In the CSS Rule-Set syntax, a 'Selector' is used to specify the portion of the document
tree that the style declaration that follows will be attached to.
A Selector is the portion of a Rule-Set that comes before the style Declaration Block
embedded within curly braces ('{' and '}'.)
How will you apply more than one class per given element?
To apply more than one class per given element, the syntax is:
<p class="center bold">
This is a paragraph.
</p>
The paragraph above will be styled by the class "center" AND the class "bold".
How will you add Styles to Elements with Particular Attributes?
You can also apply styles to HTML elements with particular attributes.
The style rule below will match all input elements that have a type attribute with a
value of "text":
input[type="text"] {background-color: blue}
How will you define styles for HTML elements with the id selector?
You can define styles for HTML elements with the id selector. The id selector is defined
as a #.
The style rule below will match the element that has an id attribute with a value of
"green":
#green {color: green}
The style rule below will match the p element that has an id with a value of "para1":
p#para1
{
text-align: center;
color: red
}
Aural style sheets use a combination of speech synthesis and sound effects to make the
user listen to information, instead of reading information.
Aural presentation can be used:
* by blind people
* to help users learning to read
* to help users who have reading problems
* for home entertainment
* in the car
* by print-impaired communities
The aural presentation converts the document to plain text and feed this to a screen reader
(a program that reads all the characters on the screen).
Database
A join is a temporary relationship that you can create between two tables in a database
query that do not already have an established relationship or common field with the same
fieldname or data type. Database tables that are joined in a query are related in that query
only, and nowhere else. The type of join that you use indicates which records the query
will select or perform the chosen actions on.
Note: Creating a query join will not establish a permanent relationship between the
tables.
The primary key of a relational table uniquely identifies each record in the table. It can
either be a normal attribute that is guaranteed to be unique (such as Social Security
Number in a table with no more than one record per person) or it can be generated by the
DBMS (such as a globally unique identifier, or GUID, in Microsoft SQL Server). Primary
keys may consist of a single attribute or multiple attributes in combination.
Which ever key is help us to identify a record uniquely in a database table is called
primary key.
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 Form
The 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 Form
Where 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 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
object-oriented-programming
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.
Functions are written sequentially, so that a change in programming can affect any code
that follows it.
If a function is used multiple times in a system (i.e., a piece of code that manages the
date), it is often simply cut and pasted into each program (i.e., a change log, order
function, fulfillment system, etc). If a date change is needed (i.e., Y2K when the code
needed to be changed to handle four numerical digits instead of two), all these pieces of
code must be found, modified, and tested.
Code (sequences of computer instructions) and data (information on which the
instructions operates on) are kept separate. Multiple sets of code can access and modify
one set of data. One set of code may rely on data in multiple places. Multiple sets of code
and data are required to work together. Changes made to any of the code sets and data
sets can cause problems through out the system.
Object-Oriented programming takes a radically different approach:
Code and data are merged into one indivisible item – an object (the term "component"
has also been used to describe an object.) An object is an abstraction of a set of real-world
things (for example, an object may be created around "date") The object would contain
all information and functionality for that thing (A date
object it may contain labels like January, February, Tuesday, Wednesday. It may contain
functionality that manages leap years, determines if it is a business day or a holiday, etc.,
See Fig. 1). Ideally, information about a particular thing should reside in only one place
in a system. The information within an object is encapsulated (or hidden) from the rest of
the system.A system is composed of multiple objects (i.e., date function, reports, order
processing, etc., See Fig 2). When one object needs information from another object, a
request is sent asking for specific information. (for example, a report object may need to
know what today’s date is and will send a request to the date object) These requests are
called messages and each object has an interface that manages messages.
OO programming languages include features such as "class", "instance", "inheritance",
and "polymorphism" that increase the power and flexibility of an object.
What’s the difference between accessing a class method via -> and via ::?
:: is allowed to access methods that can perform static operations, i.e. those, which do not
require object initialization.
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 whichnames 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.
class mylinkage
{
private:
mylinkage * prev;
mylinkage * next;
protected:
friend void set_prev(mylinkage* L, mylinkage* N);
void set_next(mylinkage* L);
public:
mylinkage * succ();
mylinkage * pred();
mylinkage();
};
void mylinkage::set_next(mylinkage* L) { next = L; }
void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }
Friends in other classes
It is possible to specify a member function of another class as a friend as follows:
class C
{
friend int B::f1();
};
class B
{
int f1();
};
It is also possible to specify all the functions in another class as friends, by specifying the
entire class as a friend.
class A
{
friend class B;
};
Friend functions allow binary operators to be defined which combine private data in a
pair of objects. This is particularly powerful when using the operator overloading features
of C++. We will return to it when we look at overloading.
XML
XML HTML
User definable tags Defined set of tags designed for
web display
Content driven Format driven
End tags required for well formed End tags not required
documents
Quotes required around attributes Quotes not required
values
Slash required in empty tags Slash not required
What is XML?
XML (Extensible Markup Language) is a standard for creating markup languages which
describe the structure of data. It is not a fixed set of elements like HTML, but rather, it is
like SGML (Standard Generalized Markup Language) in that it is a metalanguage, or a
language for describing languages. XML enables authors to define their own tags.
General Web
An online payment gateway is the interface between your merchant account and your
Web site. The online payment gateway allows you to immediately verify credit card
transactions and authorize funds on a customer's credit card directly from your Web site.
It then passes the transaction off to your merchant bank for processing, commonly
referred to as transaction batching.
server-side scripts are executed by the web server when the user requests a document.
They produce output in a format understandable by web browsers (usually HTML),
which is then sent to the user's computer. The user cannot see the script's source code
(unless the author publishes the code separately), and may not even be aware that a script
was executed. The documents produced by server-side scripts may, of course, contain
client-side scripts.
Answer 1:
MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of
e-mail. However browsers also uses MIME standard to transmit files.
MIME has a header which is added to a beginning of the data. When browser sees such
header it shows the data as it would be a file (for example image)
Some examples of MIME types:
audio/x-ms-wmp
image/png
aplication/x-shockwave-flash
Answer 2:
Multipurpose Internet Mail Extensions.
WWW's ability to recognize and handle files of different types is largely dependent on
the use of the MIME (Multipurpose Internet Mail Extensions) standard.
The standard provides for a system of registration of file types with information about the
applications needed to process them. This information is
incorporated into Web server and browser software, and enables the automatic
recognition and display of registered file types. …
Client-side scripting generally refers to the class of computer programs on the web that
are executed client-side, by the user's web browser, instead of server-side (on the web
server). This type of computer programming is an important part of the Dynamic HTML
(DHTML) concept, enabling web pages to be scripted; that is, to have different and
changing content depending on user input, environmental conditions (such as the time of
day), or other variables.Web authors write client-side scripts in languages such as
JavaScript (Client-side JavaScript), which is based on several standards:
Client-side scripts are often embedded within an HTML document, but they may also be
contained in a separate file, which is referenced by the document (or documents) that use
it. Upon request, the necessary files are sent to the user's computer by the web server (or
servers) on which they reside. The user's web browser executes the script, then displays
the document, including any visible output from the script. Client-side scripts may also
contain instructions for the browser to follow if the user interacts with the document in a
certain way, e.g., clicks a certain button. These instructions can be followed without
further communication with the server, though they may require such communication.
By viewing the file that contains the script, users may be able to see its source code.
Many web authors learn how to write client-side scripts partly by examining the source
code for other authors' scripts.
A content management system (CMS) is a system used to manage the content of a Web
site.[1] Content management systems are deployed primarily for interactive use by a
potentially large number of contributors.The content managed includes computer files,
image media, audio files, electronic documents and web content. The idea behind a CMS
is to make these files available inter-office, as well as over the web.
A web content management system is a content management system with additional
features to ease the tasks required to publish web content to web sites.
Web content management systems are often used for storing, controlling, versioning, and
publishing industry-specific documentation such as news articles, operators' manuals,
technical manuals, sales guides, and marketing brochures. A content management system
may support the following features:
* only of documents and multimedia material
* Identification of all key users and their content management roles
* The ability to assign roles and responsibilities to different content categories or types.
* Definition of the content workflow tasks, often coupled with event messaging so that
content managers are alerted to changes in content.
* The ability to track and manage multiple versions of a single instance of content.
* The ability to publish the content to a repository to support access to the content.
Increasingly, the repository is an inherent part of the system, and incorporates enterprise
search and retrieval.
* Some content management systems do allow the textual aspect of content to be
separated to some extent from formatting. For example the CMS may automatically set
default color, fonts, or layouts.
what is a mashup?
Mashups are an exciting genre of interactive Web applications that draw upon content
retrieved from external data sources to create entirely new and innovative services. They
are a hallmark of the second generation of Web applications informally known as Web
2.0.
A mashup is a website or application that combines content from more than one source
into an integrated experience.
In technology, a mashup is a web application that combines data from more than one
source into a single integrated tool; an example is the use of cartographic data from
Google Maps to add location information to real-estate data from Craigslist, thereby
creating a new and distinct web service that was not originally provided by either source.
What is a template?
A template is a framework for web pages and sites. Templates for web pages work much
like templates in Microsoft Word, or any other word processing application.
===========================================
What are the differences between Get and post methods in form submitting.
give the case where we can use get and we can use post methods?
The HTML 2.0 specification says, in section Form Submission (and the HTML 4.0
specification repeats this with minor stylistic changes):
–>If the processing of a form is idempotent (i.e. it has no lasting observable effect on the
state of the world), then the form method should be GET. Many database searches
have no visible side-effects and make ideal applications of query forms.
–
–>If the service associated with the processing of a form has side effects (for example,
modification of a database or subscription to a service), the method should be POST.
–> If the method is “get” - -, the user agent takes the value of action, appends a ? to it,
then appends the form data set, encoded using the application/x-www-form-urlencoded
content type. The user agent then traverses the link to this URI. In this scenario, form data
are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post transaction using the
value of the action attribute and a message created according to the content type specified
by the enctype attribute.
GET is (in theory) the preferred method for idempotent operations, such as querying a
database, though it matters little if you’re using a form. There is a further practical
constraint that many systems have built-in limits to the length of a GET request they can
handle: when the total size of a request (URL+params) approaches or exceeds 1Kb, you
are well-advised to use POST in any case.I would prefer POST when I don’t want the
status to be change when user resubmits. And GET when it does not matter.
Who is the father of PHP and explain the changes in PHP versions?
Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer
supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4
is the current generation of PHP, which uses the Zend engine under the hood. PHP 5 uses
Zend engine 2 which, among other things, offers many additionalOOP features
How can we submit a form without a submit button?
The main idea behind this is to use Java script submit() function in order to submit the
form without explicitly clicking any submit button. You can attach the
document.formname.submit() method to onclick, onchange events of different inputs and
perform the form submission. You can even built a timer function where you can
automatically submit the form after xx seconds once the loading is done (can be seen in
online test sites).
In how many ways we can retrieve the data in the result set of MySQL using PHP?
You can do it by 4 Ways
1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc
What is the difference between mysql_fetch_object andmysql_fetch_array?
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).
What is the difference between $message and $$message?
It is a classic example of PHP’s variable variables. take the following example.$message
= “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a simple PHP
variable that we are used to. But the $$message is not a very familiar face. It creates a
variable name $mizan with the value “is a moderator of PHPXperts.” assigned. break it
like this${$message} => $mizanSometimes it is convenient to be able to have variable
variable names. That is, a variable name which can be set and used dynamically.
How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP?
preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);
echo $found[1];
How can we create a database using PHP and MySQL?
We can create MySQL database with the use of mysql_create_db(“Database Name”)
What are the differences between require and include,include_once and
require_once?
The include() statement includes and evaluates the specified file.The documentation
below also applies to require(). The two constructs are identical in every way except how
they handle failure. include() produces a Warning while require() results
in a Fatal Error. In other words, use require() if you want a missing file to halt processing
of the page. include() does not behave this way, the script will continue regardless.The
include_once() statement includes and evaluates the specified file during the execution
of the script. This is a behavior similar to the include() statement, with the only
difference being that if the code from a file has already been included, it will not be
included again. As the name suggests, it will be included just once.include_once()
should be used in cases where the same file might be included and evaluated more than
once during a particular execution of a script, and you want to be sure that it is included
exactly once to avoid problems with function redefinitions, variable value reassignments,
etc.require_once() should be used in cases where the same file might be included and
evaluated more than once during a particular execution of a script, and you want to be
sure that it is included exactly once to avoid problems with function redefinitions,
variable value reassignments, etc.
PayPal PHP
SDK : http://www.paypaldev.org
The PHP script was loaded by the Zend Engine and compiled into Zend opcode.
Opcodes, short for operation codes, are low level binary instructions. Then the opcode
was executed and the HTML generated sent to the client. The opcode was flushed from
memory after execution.Today, there are a multitude of products and techniques to help
you speed up this process. In the following diagram, we show the how modern
PHP scripts work; all the shaded boxes are optional.
PHP Scripts are loaded into memory and compiled into Zend opcodes.
What are the current versions of apache, PHP, and MySQL?
As of February, 2007 the current versions are PHP: php5.2.1
MySQL: MySQL 5.2,Apache: Apache 2.2.4
Note: visit www.php.net,
http://dev.mysql.com/downloads/mysql/,
www.apache.org to get current versions.
What are the reasons for selecting lamp (Linux, apache, MySQL,PHP) instead of
combination of other software programs, servers and operating systems?
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.
How can we encrypt and decrypt a data present in a MySQL table
using MySQL?
AES_ENCRYPT () and AES_DECRYPT ()
How can we encrypt the username and password using PHP?
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()
What are the features and advantages of object-oriented programming?
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
What are the differences between procedure-oriented languages and
object-oriented languages?
Traditional programming has the following characteristics:Functions are written
sequentially, so that a change in programming can affect any code that follows it.
If a function is used multiple times in a system (i.e., a piece of code that manages the
date), it is often simply cut and pasted into each program (i.e., a change log, order
function, fulfillment system, etc).If a date change is needed (i.e., Y2K when the code
needed to be changed to handle four numerical digits instead of two), all these pieces of
code must be found, modified, and tested.Code (sequences of computer instructions) and
data (information on which the instructions operates on) are kept separate. Multiple sets
of code can access and modify one set of data. One set of code may rely on data in
multiple places. Multiple sets of code and data are required to work together. Changes
made to any of the code sets and data sets can cause problems through out the
system.Object-Oriented programming takes a radically different approach:Code and data
are merged into one indivisible item – an object (the term “component” has also been
used to describe an object.) An object is an abstraction of a set of real-world things (for
example, an object may be created around “date”) The object would contain all
information and functionality for that thing (A date object it may contain labels like
January, February, Tuesday, Wednesday.It may contain functionality that manages leap
years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information
about a particular thing should reside in only one place in a system.The information
within an object is encapsulated (or hidden) from the rest of the system.A system is
composed of multiple objects (i.e., date function, reports,order processing, etc., See Fig
2). When one object needs information from another object, a request is sent asking for
specific information.(for example, a report object may need to know what today’s date is
and will send a request to the date object) These requests are called messages and each
object has an interface that manages messages.OO programming languages include
features such as “class”, “instance”,“inheritance”, and “polymorphism” that increase the
power and flexibility of an object.
What is the use of friend function?
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.
What are the different types of errors in PHP?
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.
What are the differences between PHP 3 and PHP 4 and PHP 5?
Please read the release notes at http://www.php.net.
How can we convert asp pages to PHP pages?
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./
What is the functionality of the function htmlentities?
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.
How can we get second of the current time using date function?
$second = date(”s”);
How can we convert the time zones using PHP?
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>';?>
What is meant by urlencode and urldocode?
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.
What is the difference between the functions unlink and unset?
unlink() deletes the given file from the file system.unset() makes a variable undefined.
How can we register the variables into a session?
$_SESSION[’name’] = “Mizan”;
How can we take a backup of a MySQL table and how can we restore it. ?
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-infoDon’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!
How can we optimize or increase the speed of a MySQL select query?
How many ways can we get the value of current session id?
session_id() returns the session id for the current session.
How can we destroy the session, how can we unset the variable of a session?
session_unregister — Unregister a global variable from the current session
session_unset — Free all session variables
How can we destroy the cookie?
Set the cookie in past.
How many ways we can pass the variable through the navigation
between the pages?
• GET/QueryString
• POST
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);
What are the other commands to know the structure of table using
MySQL commands except explain command?
describe Table-Name;
Give the syntax of Grant and Revoke commands?
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
Explain Normalization concept?
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 Form
Advantages
Classes 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 information
Disadvantages
This method can not control styles for multiple documents at once
Inline Styles
Advantages
Disadvantages
Condition1: Delete all the rows and insert another row then.
What is the starting value for this auto incremented field user_pri_id ,
Condition2: Delete the last row(having the field value 999) and
insert another row then. What is the value for this auto incremented
field user_pri_id
In both cases let the value for auto increment field be n then next
row will have value n+1 i.e. 1000
What are the advantages/disadvantages of MySQL and PHP?
Both of them are open source software (so free of cost), support
cross platform. php is faster then ASP and JSP.
What is the difference between GROUP BY and ORDER BY in Sql?
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
em {color: blue; } However, if you use a descendant selector, you can refine the
<em> elements that you select. The rule below will only select <em> elements that
are descendants of <p> elements. If this rule is applied, the <em> element within
the <h1> will not be colored blue.
p em {color: blue; } You can also jump levels in the document tree structure to
select descendants. For example, the following code:
<body>
<p>Lorem ipsum dolor <em>sit</em> amet.</p>
<ul>
<li>item 1</li>
<li>item 2</li>
<li><em>item 3</em></li>
</ul>
</body> The document tree (with a third-level <em> element highlighted) would
be:
Using the following rule you can isolate any <em> element inside a <ul> element,
without having to describe the <li> element. If this rule is applied, any <em>
element within a <ul> element will be colored blue. However, the <em> element
within the <p> will not be colored blue:
Child selectors
A child selector is used to select an element that is a direct child of another element
(parent). Child selectors will not select all descendants, only direct children.
For example, you may wish to target an <em> that is a direct child of a <div>, but
not other <em> elements that are descendants of the <div>. A sample document
could contain the following code:
<body>
<h1>Heading <em>text</em></h1>
<div>
This is some <em>text</em>
<p>This is a paragraph of <em>text</em></p>
</div>
</body>
The document tree (highlighting the <em> that is a child of the <div> would be:
Using the following rule you can target any <em> element that is a child of the
<div>. Other <em> elements that are descendants but not direct children of the
<div> will not be targeted.
OR
<HTML>
<HEAD>
<TITLE>Estate Agent</TITLE>
<SCRIPT>
function House(rooms,price,garage) {
this.rooms=rooms;
this.price=price;
this.garage=garage;
}
house1=new House(4,100000,false);
house2=new House(5,200000,true);
with (house1) document.write(’House 1 has ‘+rooms+’ rooms, ‘+(garage?’a':’no’)+’
garage, and costs £’+price+’<BR>’);
with (house2) document.write(’House 2 has ‘+rooms+’ rooms, ‘+(garage?’a':’no’)+’
garage, and costs £’+price+’<BR>’);
</SCRIPT>
</HEAD>
</HTML>
We define a House function that takes three parameters, rooms, price and garage.
The function uses the this keyword to create an object.
When we call the House function, we assign the result to our variable, which
becomes an object.
house1=new Object();
house1.rooms=4;
house1.price=100000;
house1.garage=false;
We would have to type this in for all houses, which would be very tedious and is why
we use the class structure instead.
When we display the details for a house, I have introduced the ternary operator, ‘?:’.
The ternary operator is a compacted version of:
(garage?’a':’no’) means if garage is true, return ‘a’ else return ‘no’. Using the ternary
operator removes a line of code, and avoids having to create a new variable.
Class Methods
The House class we have so far defined only contains object properties. We could add
a method to replace the document.write() action we used before. (See example)
<HTML>
<HEAD>
<TITLE>Estate Agent 2</TITLE>
<SCRIPT>
function House(name,rooms,price,garage) {
this.name=name;
this.rooms=rooms;
this.price=price;
this.garage=garage;
this.view=view;
}
function view() {
with (this) document.write(name+’ has ‘+rooms+’ rooms, ‘+(garage?’a':’no’)+’
garage, and costs £’+price+’<BR>’);
}
house1=new House(’House 1′,4,100000,false);
house2=new House(’Big House’,5,200000,true);
house1.view();
house2.view();
</SCRIPT>
</HEAD>
</HTML>
Much better!
Note how we must add another property, name, so that we can identify the house in
question. This offers more flexibility than re-using the variable name, and the
variable name is inaccessible anyway, i.e. it is very difficult, if not impossible, to get
the view() function to use the string ‘house1′.
Are namespaces are there in JavaScript?
A namespace is a container and allows you to bundle up all your functionality using a
unique name. In JavaScript, a namespace is really just an object that you’ve
attached all further methods, properties and objects. But it is not always necessary
to use namespace.
What is JSON? What are the notations used in JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is
easy for humans to read and write. It is easy for machines to parse and generate. It
is based on a subset of the JavaScript Programming Language, Standard ECMA-262
3rd Edition - December 1999. JSON is a text format that is completely language
independent but uses conventions that are familiar to programmers of the C-family
of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
These properties make JSON an ideal data-interchange language.
How you provide security for PHP application?
There are many ways to accomplish the security tasks but the most common 7 ways
are1. Validate Input. Never trust your user and always filter input before taking it to
any operation.2. Provide access control.3. Session ID protection4. preventing Cross
Site Scripting (XSS) flaws
6. Turning off error reporting and exposing to the site for hackers. Instead use log
file to catch exceptions
7. Effective Data handling
What is SQL Injection in PHP security?
SQL injection attacks are extremely simple to defend against, but many applications
are still vulnerable. Consider the following SQL statement:
<?php
$sql = "INSERT
INTO users (reg_username,
reg_password,
reg_email)
VALUES ('{$_POST['reg_username']}’,
‘$reg_password’,
‘{$_POST['reg_email']}’)”;
?>
This query is constructed with $_POST, which should immediately look suspicious.
Assume that this query is creating a new account. The user provides a desired
username and an email address. The registration application generates a temporary
password and emails it to the user to verify the email address. Imagine that the user
enters the following as a username:
This certainly doesn’t look like a valid username, but with no data filtering in place,
the application can’t tell. If a valid email address is given (shiflett@php.net, for
example), and 1234 is what the application generates for the password, the SQL
statement becomes the following:
<?php
$sql = "INSERT
INTO users (reg_username,
reg_password,
reg_email)
VALUES ('bad_guy', 'mypass', ''),
('good_guy',
'1234',
'shiflett@php.net')"; ?>
Rather than the intended action of creating a single account (good_guy) with a valid
email address, the application has been tricked into creating two accounts, and the
user supplied every detail of the bad_guy account.
While this particular example might not seem so harmful, it should be clear that
worse things could happen once an attacker can make modifications to your SQL
statements.
For example, depending on the database you are using, it might be possible to send
multiple queries to the database server in a single call. Thus, a user can potentially
terminate the existing query with a semicolon and follow this with a query of the
user’s choosing.
MySQL, until recently, does not allow multiple queries, so this particular risk is
mitigated. Newer versions of MySQL allow multiple queries, but the corresponding
PHP extension (ext/mysqli) requires that you use a separate function if you want to
send multiple queries (mysqli_multi_query() instead of mysqli_query()). Only
allowing a single query is safer, because it limits what an attacker can potentially do.
• Filter your data.This cannot be overstressed. With good data filtering in place,
most security concerns are mitigated, and some are practically eliminated.
• Quote your data.If your database allows it (MySQL does), put single quotes
around all values in your SQL statements, regardless of the data type.
Escape your data.Sometimes valid data can unintentionally interfere with the format
of the SQL statement itself. Use mysql_escape_string() or an escaping function
native to your particular database. If there isn’t a specific one, addslashes() is a
good last resort.
What is cross site Scripting?
To understand what Cross Site Scripting is, let’s see a usual situation,
common to many sites. Let’s say we are taking some information
passed in on a querystring (the string after the (?) character within a
URL), with the purpose of displaying the content of a variable, for
example, the visitor’s name:
http://www.yourdomain.com/welcomedir/welcomepage.php?name=John
As we can see in this simple querystring, we are passing the visitor’s
name as a parameter in the URL, and then displaying it on our
“welcomepage.php” page with the following PHP code:
<?php
?>
The result of this snippet is shown below:
http://www.yourdomain.com/welcomedir/
welcomepage.php?name=John
with something like this:
http://www.yourdomain.com/welcomedir/
welcomepage.php?name=
<script language=javascript>alert
(‘Hey, you are going to be hijacked!’);</script>
Do you remember the PHP code included in our “welcome.php” page? Yes, you’re
correct. When we modify the querystring, the following code is executed:
<?php
?>
The output of this code is an alert JavaScript box telling you “Hey, you are going be
hijacked!” after the “Welcome to our site” phrase.
Very ugly stuff, right? That’s a simple example of the Cross Site Scripting
vulnerability. This means that any pasted JavaScript code into the URL will be
executed happily with no complaints at all.
Which method do you follow to get a record from a million records?
(Searching, …. not from database, from an array in php)
use array_search(), array_keys(), array_values(), array_key_exists(), and
in_array().
93. Which sorting method is lowest time consumable?
HeapSort, Merge sort are the lowest time consumable sorting algorithm.
What are the differences between GET and POST methods in form submitting, give
the case where we can use get and we can use post methods?
Answer:
On the server side, the main difference between GET and POST is where the submitted is
stored. The $_GET array stores data submitted by the GET method. The $_POST array
stores data submitted by the POST method.On the browser side, the difference is that data
submitted by the GET method will be displayed in the browser's address field. Data
submitted by the POST method will not be displayed anywhere on the browser.GET
method is mostly used for submitting a small amount and less sensitive data. POST
method is mostly used for submitting a large amount or sensitive data.
Who is the father of php and explain the changes in php versions?
Answer:
Rasmus Lerdorf for version changes go to http://php.net/.Marco Tabini is the founder and
publisher of php|architect.
How many ways we can retrieve the date in result set of mysql Using php?
Answer:
As individual objects so single record or as a set or arrays.