Below are the list of questions those asked many times by the interviewer. Here I tried to give most optimistic and preferable solution to attract interviewer to get crack the interview.
Q. PHP latest stable version.
Ans : 5.4.15, 5.3.25(Old stable)
@ diffrence between php 5.3 and php5.4
- Support for traits has been added.
- Short array syntax has been added, e.g. $a = [1, 2, 3]; or $a = ['one' => 1, 'two' => 2, 'three' => 3];
- Function array dereferencing has been added, e.g. foo()[0].
- Closures now support $this.
- <?= is now always available, regardless of the short_open_tag php.ini option.
- Class member access on instantiation has been added, e.g. (new Foo)->bar().
- Class::{expr}() syntax is now supported.
- Binary number format has been added, e.g. 0b001001101.
- Improved parse error messages and improved incompatible arguments warnings.
- The session extension can now track the upload progress of files.
- Built-in development web server in CLI mode.
==
Q. Tell us difference between different versions of MySQL ?
Ans.
mysql 4.0 (end-of-life)
- full support for union
- full support for inner and outer joins
- upgraded myisam tables to replace isam tables
- query cache
mysql 4.1 (end-of-life)
- added support for per-table character sets and collations (but you absolutely need to use a later release in this series because early versions had some evil problems with multibyte character set support in certain functions)
- better password hashing
- subqueries (early versions in the 4.1 series did not allow some clauses inside subqueries, like LIMIT. this restriction was eventually lifted.)
- spatial extensions
- clustering using the ndbcluster in-memory tables
mysql 5.0 (current stable release)
- added support for per-column character sets and collations
- stored procedures
- triggers (in early versions of the mysql 5.0 and 5.1 series, triggers could not refer to any data other than the row that caused the trigger or run non-deterministic procedures. in later releases, this restriction was lifted and triggers can run just about any query from any table, and just about any procedure.)
- views
- HUGELY improved replication
- INFORMATION_SCHEMA database added (allows access to database objects via standard SELECT statements)
mysql 5.1 (beta)
- horizontal partitioning
- event scheduling (like a built-in cron)
- XML data manipulation in VARCHAR and TEXT columns
- disk based clustering
==
Q.How many ways to find n th highest from sql query ?
Ans.
1. select max(Price) as price from OrderDetails where Price<(select max(Price ) from OrderDetails);
2. SELECT * FROM table_name ORDER BY column_name DESC LIMIT n - 1, 1
3 select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee )
4 select MAX(Salary) from Employee WHERE Salary <> (select MAX(Salary) from Employee )
==
Q. What are the features offered from INNODB and MYISAM engine?
InnoDB offers:
- ACID transactions
- row-level locking
- foreign key constraints
- automatic crash recovery
- table compression (read/write)
- spatial data types (no spatial indexes)
In InnoDB all data in a row except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. In InnoDB the COUNT(*)s (when WHERE, GROUP BY, or JOIN is not used) execute slower than in MyISAM because the row count is not stored internally. InnoDB stores both data and indexes in one file. InnoDB uses a buffer pool to cache both data and indexes.
MyISAM offers:
- fast COUNT(*)s (when WHERE, GROUP BY, or JOIN is not used)
- full text indexing
- smaller disk footprint
- very high table compression (read only)
- spatial data types and indexes (R-tree)
MyISAM has table-level locking, but no row-level locking. No transactions. No automatic crash recovery, but it does offer repair table functionality. No foreign key constraints. MyISAM tables are generally more compact in size on disk when compared to InnoDB tables. MyISAM tables could be further highly reduced in size by compressing with myisampack if needed, but become read-only. MyISAM stores indexes in one file and data in another. MyISAM uses key buffers for caching indexes and leaves the data caching management to the operating system.
Overall I would recommend InnoDB for most purposes and MyISAM for specialized uses only. InnoDB is now the default engine in new MySQL versions.
Starting from MySQL 5.5.5, the default storage engine for new tables is InnoDB.
==
Q. What all the types of joins available in Mysql?
Ans.
Inner joins (the typical join operation, which uses some comparison operator like = or <>). These include equi-joins and natural joins.
Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables.
Equi Join
Equi Join is a classified type of Inner Join in Mysql. Equi Join is used to combine records from two table based on the common column exists in both table.
mysql> select roseindia.firstname,roseindia.city,newstrack.firstname
-> from roseindia,newstrack where roseindia.empid=newstrack.empid;
Main difference between Self Join and Equi Join is that, In Self Join we join one table to itself rather than joining two tables. Both Self Join and Equi Join are types of INNER Join in SQL but there is subtle difference between two. Any INNER Join with equal as join predicate is known as Equi Join.
SELECT e.first_name AS 'Employee FN', e.last_name AS 'Employee LN', m.first_name AS 'Manager FN', m.last_name AS 'Manager LN'
FROM employees AS e LEFT OUTER JOIN employees AS m
ON e.manager =m.id
Outer joins. Outer joins can be a left, a right, or full outer join.
Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:
LEFT JOIN or LEFT OUTER JOIN
The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.
RIGHT JOIN or RIGHT OUTER JOIN.
A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.
FULL JOIN or FULL OUTER JOIN.
FULL OUTER JOIN is not supported in MySQL.
A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
CROSS JOIN
Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.
Cross Joins produce results that consist of every combination of rows from two or more tables. That means if table A has 6 rows and table B has 3 rows, a cross join will result in 18 rows. There is no relationship established between the two tables – you literally just produce every possible combination.
The SQL CROSS JOIN produces a result set which is the number of rows in the first table multiplied by the number of rows in the second table, if no WHERE clause is used along with CROSS JOIN. This kind of result is called as Cartesian Product.
If, WHERE clause is used with CROSS JOIN, it functions like an INNER JOIN.
An alternative way of achieving the same result is to use column names separated by commas after SELECT and mentioning the table names involved, after a FROM clause.
Natural JOIN
SELECT * FROM users NATURAL JOIN post
The repeated column is avoided.
==
Q . What is index and types of index in mysql?
Ans.
INDEXES
MySQL supports three general types of indexes:
A primary key is an index
A unique index is similar to a primary key, except that it can be allowed to contain NULL values.
A non-unique index is an index in which any key value may occur multiple times.
There are also more specialized types of indexes:
A FULLTEXT index is specially designed for text searching.
==
Q. What is union ?
Ans.
UNION
UNION used to combine two or more result sets from multiple SQL SELECT statements into a single result set.
SELECT customerNumber id, contactLastname name
FROM customers
UNION
SELECT employeeNumber id,firstname name
FROM employees
There are some rules that you need to follow in order to use the UNION operator:
- The number of columns appears in the corresponding SELECT statements must be equal.
- The columns appear in the corresponding positions of each SELECT statement must have the same data type or at least convertible data type.
==
Q. What is having clause in Mysql?
HAVING
The MySQL HAVING clause specifies a filter condition for a group of record or an aggregate.
HAVING clause applies to groups of records as a whole, while the WHERE clause applies to individual row.
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.
SELECT ordernumber,
sum(quantityOrdered) AS itemsCount,
sum(priceeach) AS total
FROM orderdetails
GROUP BY ordernumber
HAVING total > 1000
==
Q. What is sequence of where, group by, having, limit, order by in sql query?
Ans.
SELECT values_to_display
FROM table_name
WHERE expression
GROUP BY how_to_group
HAVING expression
ORDER BY how_to_sort
LIMIT row_count;
==
Q. what is the sql query to find second highest record?
Ans.
Second highest
Second maximum salary using sub query and IN clause
SELECT max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary) FROM Employee);
Here is another SQL query to find second highest salary using subquery and < operator instead of IN clause:
SELECT max(salary) FROM Employee WHERE salary < (SELECT max(salary) FROM Employee);
Second maximum salary using LIMIT keyword of MYSQL database
SELECT salary FROM (SELECT salary FROM Employee ORDER BY salary DESC LIMIT 2) AS emp ORDER BY salary LIMIT 1;
select salary from employee order by desc salary limit 1, 1;
=========
Q. Tell us states of ajax?
Ans.
Ajax
5 readyStates
0 = uninitialized , The request is uninitialized (before you've called open()).
1 = loading , The request is set up, but not sent (before you've called send()).
2 = loaded, The request was sent and is in process (you can usually get content headers from the response at this point).
3 = interactive , The request is in process; often some partial data is available from the response, but the server isn't finished with its response.
4 = complete , The response is complete; you can get the server's response and use it.
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "serverTime.php", true);
ajaxRequest.send(null);
=========
Jquery questions
http://jquerybyexample.blogspot.com/2011/08/mostly-asked-jquery-interview-questions.html
jQuery - bind() vs live() vs delegate() methods
http://jquerybyexample.blogspot.com/2010/08/bind-vs-live-vs-delegate-function.html
jquery
==
Q. How to change color and width of html element using jquery?
Ans.
$(this).css("color","red");
$( this ).css( "width","+=200" );
JQuery("body").css("background-color","red")
==== using javascript
function changeBGC(color){
document.body.style.background = color;
document.bgColor = color;
}
==
Q. What is closer in javascript?
Ans. Coming soon.
closers - javascript
==
Design patterns
1. Singelton patter : One instance of a class.Like static
2. Factory pattern : interface or abstract class, coupling of classes using inheritance
For example a graphical application works with shapes. In our implementation the drawing framework is the client and the shapes are the products. All the shapes are derived from an abstract shape class (or interface).
# Sometimes, an Application (or framework) at runtime, cannot anticipate the class of object that it must create. The Application (or framework) may know that it has to instantiate classes, but it may only know about abstract classes (or interfaces), which it cannot instantiate. Thus the Application class may only know when it has to instantiate a new Object of a class, not what kind of subclass to create.
==
Q: What are the uses of SOAP?
Ans.
SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages.
For example, SOAP can make use of any transport protocol not just HTTP(S), "SOAP offers more options when security is concerned", "SOAP offers reliable messaging" etc etc. REST on the other hand permits many different types of data formats, REST allows better support for browsers because of the JSON format, REST has better performance etc etc etc.
Dear! cURL is a computer software project providing a library and command-line tool for transferring data using various protocols. The cURL project produces two products, curl uses libcurl, it supports a range of common Internet protocols, currently including HTTP, HTTPS, FTP, FTPS, GOPHER, LDAP, DICT, TELNET and FILE.
SOAP is an XML-based messaging protocol. It defines a set of rules for structuring messages that can be used for simple one-way messaging but is particularly useful for performing RPC-style (Remote Procedure Call) request-response dialogues. It is not tied to any particular transport protocol though HTTP is popular. Nor is it tied to any particular operating system or programming language so theoretically the clients and servers in these dialogues can be running on any platform and written in any language as long as they can formulate and understand SOAP messages.
==
Q: What is TML5?
Ans
HTML5 will be the new standard for HTML.
In HTML5 there is only one <!doctype> declaration : <!DOCTYPE html>
======
Q. Explain about file handing in php?
Ans.
PHP : file handling, GD library, payment gateway(paypal), array funtions, string functions,interface, abstract, inheritance, magic methods,session, cookies,
File handling
- fopen: To open a file in a particular mode, like r: read, w: write, a: append etc.
- feof: To check whether the pointer has reached at the end of the file or not.
- fclose: To close the file.
- fgets: To extract the content line by line.
- fgetc: To extract the content character by character.
==
Q. Explain about GD library in php?
Ans.
The PHP GD Library is one of the most used image-processing libraries used in the PHP programs. IT is one of the robust library to create GIF, JPG and PNG images through PHP program. You can use this library to create, create thumbnail, resize, crop image on the fly.
Written in 'C'
$img = imagecreate(200, 200);
$red = imagecolorallocate($img, 255, 0, 0);
$black = imagecolorallocate($img, 0, 0, 0);
imagearc($img, 100, 100, 150, 150, 0, 360, $black);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
==
Q Explain about different payment options available in Payapl?
Ans.
PayPal Express Checkout
If you use PayPal Express Checkout, when your customers check out, they will be directed to a page that requires them to log into their PayPal account or create a new one. Therefore, this is the best option if you anticipate that most of your customers either have a PayPal account or will sign up for an account on checkout.
PayPal Website Payments Standard (Payments Standard)
If you use PayPal Website Payments Standard, when your customers check out, they will be directed to a page that allows them to log into their PayPal account or pay by credit card without having to sign up for a PayPal account.
PayPal Direct payment plug-in is direct credit card payment plug-in which lets customers shop and pay directly in PBA-S system with their credit cards (without redirecting to PayPal site).
==
Q. What is DDL, DML and DCL ?
Ans.
If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.
How do you start and stop MySQL on Windows? - net start MySQL, net stop MySQL
What’s the default port for MySQL Server? - 3306
Transaction :
A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail.
Transactions have the following four standard properties, usually referred to by the acronym ACID:
COMMIT and ROLLBACK:
These two keywords Commit and Rollback are mainly used for MySQL Transactions.
* When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect.
* If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state.
==
Q. Solve below queries ?
Ans.
How would you write a query to select all teams that won either 2, 4, 6 or 8 games?
SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8)
How would you select all the users, whose phone number is null?
SELECT user_name FROM users WHERE ISNULL(user_phonenumber);
An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time.
==
Q. Explain terms advance search, trigers, stored procedures,JOINS, self joins, views
Ans.
Trigger (http://www.mysqltutorial.org/sql-triggers.aspx)
A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. The trigger becomes associated with the table named tbl_name, which must refer to a permanent table.
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END;
---
A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The CALL SQL statement is used to execute a stored procedure.
$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;");
$mysqli->query("CALL p(1)");
---
Cursor
A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time.
DELIMITER $$
create procedure curdemo(id int)
begin
DECLARE name varchar(10);
DECLARE cur1 CURSOR FOR SELECT stu_name from stu_table where stu_id =id;
OPEN cur1;
Fetch cur1 into name;
select name;
close cur1;
end$$
DELIMITER ;
Cursor is used to perform an action on SQL statements on a row by row Basis. It can be viewed as a pointer to one row in a set of rows.
Stored procedure is a set of SQL statement grouped together and it is a pre-compiled one.
Stored Procedure :
SP is a set of SQL Statements that resides in server. Advantage of SP is just that it is pre compiled and available in the server. So, whenever this SP is called, its executed instantly since its already been compiled. This makes the faster performance while executing the SP.
We can also make the SP recompile when ever it is called by using
"With Recompile" keyword while creating the SP. So whenever the SP is called it is recompiled and then execute.
Cursors:
Cursors are add on feature of SP , for row by row validations.
For instance : You have a list of employees belong to various department. For calculating the bonus % which varies for department to department, you use cursors to calculate Bonus.
=====
Linux : fadora commands
=====
count all the elemenents from multidu=imentional array.
$count = 0;
foreach ($array as $type) {
$count+= count($type);
}
==
PHP run from command prompt
JSON funtion and use
===
pagination short sweet script
==
constructors
==
fadora commnads
==
directory and file listing
scandir(), readdir(),is_dir(), is_file().
==
mysql datatypes.
==
php operators
==
differencce in print and echo
1. echo can take more than one parameter when used without parentheses. The syntax is echo expression [, expression[, expression] ... ]. Note that echo ($arg1,$arg2) is invalid.
print only takes one parameter.
2. echo does not return any value - void echo ( string $arg1 [, string $... ] )
print always returns 1 (integer) - int print ( string $arg )
3. print and echo are more or less the same; they are both language constructs that display strings.
==
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.
* KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for making sure certain queries can run quickly.
* UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to speed up queries, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow this distinct values rule to be broken when inserting or updating data.
Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.
* PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.
Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.
* FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).
Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.
Similarities
* All of these indexes may have more than one column in them.
* With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)
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:
==========
Mysql datatype
The maximum sizes of the MySQL Blob fields are as follows:
INYBLOB L+1 bytes, where L < 28 256 bytes
BLOB L+2 bytes, where L < 216 65 kilobytes
MEDIUMBLOB L+3 bytes, where L < 224 16 megabytes
LONGBLOB L+4 bytes, where L < 232 4 gigabytes
Type Length in Bytes Minimum Value(Signed/Unsigned) Maximum Value(Signed/Unsigned)
TINYINT 1 -128 to 0 127 to 255
SMALLINT 2 -32768 to 0 32767 to 65535
MEDIUMINT 3 -8388608 to 0 8388607 to 16777215
INT 4 -2147483648 to 0 2147483647 to 4294967295
BIGINT 8 -9223372036854775808 to 0 9223372036854775807 to 18446744073709551615
Char 1
Float 4
Double 8
==
DOUBLE columns are not the same as DECIMAL columns, and you will get in trouble if you use DOUBLE columns for financial data.
DOUBLE is actually just a double precision (64 bit instead of 32 bit) version of FLOAT. Floating point numbers are approximate representations of real numbers and they are not exact. In fact, simple numbers like 0.01 do not have an exact representation in FLOAT or DOUBLE types.
The NUMERIC data type in MySQL is a synonym for DECIMAL. (If you declare a column as NUMERIC, MySQL uses DECIMAL in the definition.) Standard SQL allows for a difference between the two types, but in MySQL they are the same. In standard SQL, the precision for NUMERIC must be exactly the number of digits given in the column definition. The precision for DECIMAL must be at least that many digits but is allowed to be more. In MySQL, the precision is exactly as given, for both types.
=====
Introducing to PL/SQL Cursor (http://www.zentut.com/plsql-tutorial/plsql-cursor/)
When you work with Oracle database, you work with a complete set of rows that is also known as result set returned from SQL SELECT statement. However the application in some cases cannot work effectively with entire result set, therefore the database server needs to provide a mechanism for the application to work with one row or a subset of result set at a time. As the result, Oracle introduced Cursor concept to provide these extensions.
=====
Transaction (http://zetcode.com/databases/mysqltutorial/transactions/)
=====
.htaccess is a configuration file for use on web servers running the Apache Web Server software. When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software. These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer. These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.
.htaccess uses (https://my.justhost.com/cgi/help/htaccess)
* Alternative Index Files
* Custom Error Pages
* Stop a Directory Index From Being Shown
* Deny/Allow Certain IP Addresses
* Redirection
* Password Protection
* set php configuration - you could simply place these in the .htaccess file, but .htaccess is a viable alternative if your host doesn't allow you to touch the php.ini file.
#format
php_value setting_name setting_value
#example
php_value upload_max_filesize 10M
* url rewriting
* Setting server timezone (for Los Angeles time (Pacific time) : SetEnv TZ America/Los_Angeles )
========
Virtual host
Using Apache Virtual Host, you can run several websites on the same server.
For example, I can run both thegeekstuff.com and top5freeware.com on a single physical server that has one Apache webserver running on it.
Apache\conf\httpd.conf
Apache 2.2 - the editing of httpd.conf is only to uncomment (remove the # from the beginning of the following line:
#Include conf/extra/httpd-vhosts.conf
Everything else is entered in the file httpd-vhosts.conf, which will be located in the extra folder below the below the folder containing httpd.conf. As mentioned, the method described here will still work.
To set things up the way you'll need them, you'll need to add the following block to either your httpd.conf file, just above the virtual hosts, or to your httpd-vhosts.conf file:
<Directory "C:\ My Sites ">
Order Deny,Allow
Allow from all
</Directory>
<VirtualHost 127.0.0.1>
DocumentRoot "C:\My Sites\Site1"
ServerName site1.local
</VirtualHost>
=======
Encapsulation is the term given to the process of hiding all the details of an object that do not contribute to its essential characteristics.
Ahhh...but what are the essential characteristics of an object? Well, the common definition of an object implies that the only thing that is really essential to an object is the set of methods it can execute.
So, encapsulation hides the implementation details of the object and the only thing that remains externally visible is the interface of the object. (i.e.: the set of all messages the object can respond to)
Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object. The only way to access such an encapsulated object is via message passing: one sends a message to the object, and the object itself selects the method by which it will react to the message, determined by
=======
singelton design pattern, class
closures js
bind
Maximum size of POST data that PHP will accept.
post_max_size = 8MB
Get max size : 255character
==
diff get and post
http://www.diffen.com/difference/Get_vs_Post
===
file upload max size
upload_max_filesize = 2M
deafult port mysql :3306
mysql configuration file : /etc/mysql/my.cnf
==
Query optimization
==
What is the difference between early-binding and late-binding?
Early binding. The type of the instance is determined in the compile time. It follows that the static (declared) type of the pointer or reference is used. This is the default for all methods in C++, C, or Object Pascal.
Late binding. The type of the instance is determined in the run time. It follows that the actual type of the instance is used and the method of this type is called. This is always used for the methods in Java. In C++, the virtual keyword denotes the methods using the late binding.
Late binding gives the class polymorphic behavior. On the other hand, late binding is less effective than early binding, even though the difference may be negligible. (In C++ on PCs, the difference between the late and the early binding is usually one machine instruction per method call.)
Any method that might be overridden in any of the derived classes should use the late binding.
===
1. Difference between http and ftp protocol?
FTP, is a protocol used to upload files from a workstation to a FTP server or download files from a FTP server to a workstation.
HTTP, is a protocol used to transfer files from a Web server onto a browser in order to view a Web page that is on the Internet.
When ftp appears in a URL it means that the user is connecting to a file server and not a Web server and that some form of file transfer is going to take place.
When http appears in a URL it means that the user is connecting to a Web server and not a file server. The files are transferred but not downloaded, therefore not copied into the memory of the receiving device.
FTP is a two-way system as files are transferred back and forth between server and workstation.
HTTP is a one-way system as files are transported only from the server onto the workstation's browser.
FTP, where entire files are transferred from one device to another and copied into memory,
HTTP only transfers the contents of a web page into a browser for viewing.
FTP file uploaded is used in cases when the file size is more than 70 MB
HTTP upload is used for smaller files.
2. Synchronous and asynchrous process?
Asynchronous refers to processes that do not depend on each other's outcome, and can therefore occur on different threads simultaneously. The opposite is synchronous. Synchronous processes wait for one to complete before the next begins.
3. What is ajax?
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
4. How to call procedures in php?
You can call a stored procedure using the following syntax:
$result = mysql_query('CALL getNodeChildren(2)');
5. Diffrence in procedure and function in mysql and how to call them?
6. What is mysql connect and mysql pulling? How long the connection will exit without calling mysql_close() method? Howmany connection can be created by database at a time?
Persistent connection support was introduced in PHP 5.3 for the mysqli extension. Support was already present in PDO MYSQL and ext/mysql. The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process, rather than being created and destroyed multiple times. This reduces the overhead of creating fresh connections every time one is required, as unused connections are cached and ready to be reused.
The difference between connect() and pconnect, it is simply like a shop when u entering in shop you will open the door and take your iteam come out and close the door that is called connect() in mysql the connection to the mysql database will be automatically closed when the script terminates.
when the door of the shop is already opend and never close it is called pconnect(), open a connection with mysql_pconnect(), the connection will not be closed and will "persist" for future use.
Once you have opened a connection to your MySQL database from your PHP document, you can close it again using the mysql_close () function. Most of the time this isn't necessary, because MySQL connections are usually closed by default at the end of the script.
Persistent connects will timeout if on an non-interactive session based on the wait_timeout variable in my.cnf.
http://www.mysqlperformanceblog.com/2006/11/12/are-php-persistent-connections-evil/
7. What is iframe in html?
8. Difference in DBMS and RDBMS? Is excel and text file also can be called a database?
9. What is index? What are the types of index? How datasbe works with index? How databse will perform search operaton on a name field index?
Most MySQL indexes (PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT) are stored in B-trees.Exceptions are that indexes on spatial data types use R-trees, and that MEMORY tables also support hash indexes.
Basically an index on a table works like an index in a book (that's where the name came from):
Let's say you have a book about databases and you want to find some information about, say, storage. Without an index (assuming no other aid, such as a table of contents) you'd have to go through the pages one by one, until you found the topic (that's a full table scan). On the other hand, an index has a list of keywords, so you'd consult the index and see that storage is mentioned on pages 113-120,231 and 354. Then you could flip to those pages directly, without searching (that's a search with an index, somewhat faster).
10.What is joins? explain with example?
11.Magento :How will you show the products in cart if order gets failed from payment gateway?
12.If transaction is successful and coneection failed before returning to website, in this case how will you manage the process?
13.Cron job : If connection failed or file gets currepted in the cron job time , how will you perform the updates or maintain the state of data?
14 ORM - databse independent code?
15 Cluster index
Clustered Index: Clustered index physically rearrange the data that users inserts in your tables. It is nothing but a dictionary type data where actual data remains.
Non-Clustered Index: It Non-Clustered Index contains pointers to the data that is stored in the data page. It is a kind of index backside of the book where you see only the reference of a kind of data.
16 whar are the disadvantages of triggers?
. Triggers execute invisible to client-application application. They are not visible or can be traced in debugging code.
. Triggers executes invisibly from client-application which connects to the database server.So it is difficult to figure out what happens at the database layer.
. Triggers runs on every update made to the table therefore it adds more load to the database and cause the system to run slow.
17 connection pulling
"Connection Pooling", in which you create a series of connections a priori and keep them there for other applications to consume. In this case connections are persistent to the database but non-persistent to the applications.
18 Stateless and stateful protocol?
A stateless server is a server that treats each request as an independent transaction that is unrelated to any previous request.
The difference is in the nature of the connection they define between a client and a server.Telnet and FTP, for example are stateful protocols
A stateless server is a server that treats each request as an independent transaction that is unrelated to any previous request.
The difference is in the nature of the connection they define between a client and a server.Telnet and FTP, for example are stateful protocols.
it remembers who the user is, and what it is that they are doing.For example, when u FTP to mama, u as a client request a file for download, the FTP(mama) server can associate the request with previous ones and work out which file u requested,like sometimes it pops messages saying,"do u want to overwrite? or modify changes".It also creates a log file which u can easily view with the ws_ftp program.
19 what is Prepared statements and stored procedures?
Stored procedures are a sequence of instructions in PL/SQL language. Is a programming language implemented by some DBMS, that lets you store sequences of queries frequently applied to your model, and share the processing load with the application layer.
Prepared statements are queries written with placeholders instead of actual values. You write the query and it is compiled just once by the DBMS, and then you just pass values to place into the placeholders. The advantage of using prepared statements is that you enhance the performance considerably, and protect your applications from SQL Injection.
The difference is you cant store prepared statements. You must "prepare" them every time you need to execute one. Stored procedures, on the other hand, can be stored, associated to a schema
http://php.net/manual/en/pdo.prepared-statements.php
ex1.
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
ex2
<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $return_value\n";
?>
20 What is difference between mysql,mysqli and pdo ?
Those are differents API to access a MySQL backend
1. the mysql is the historical API
2. the mysqli is a new version of the historical API, it should perform better and have a better set of function, also the API is object oriented
3. PDO_MySQL, is the MySQL for PDO, PDO has been introduced in PHP, the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code(if you don't use specific RDBM function in your queries), also object oriented
PDO has the following advantages:
It's cross database, meaning it's the same interface for different relational databases.
It's faster.
It helps protect against SQL injections.
PHP Database Access:
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->query('SELECT * FROM myTable WHERE name = ' . $conn->quote($name));
21 MySQL stored procedure vs function, which would I use when?
ou can't mix in stored procedures with ordinary SQL, whilst with stored function you can.
e.g. SELECT get_foo(myColumn) FROM mytable is not valid if get_foo() is a procedure, but you can do that if get_foo() is a function. The price is that functions have more limitations than a procedure.
1.A procedure does not return a value. Instead, it is invoked with a CALL statement to perform an operation such as modifying a table or processing retrieved records.
2.A function is invoked within an expression and returns a single value directly to the caller to be used in the expression.
3.You cannot invoke a function with a CALL statement, nor can you invoke a procedure in an expression.
CREATE PROCEDURE proc_name ([parameters])
[characteristics]
routine_body
CREATE FUNCTION func_name ([parameters])
RETURNS data_type // diffrent
[characteristics]
routine_body
===
Manage session time
ini_set('session.gc_maxlifetime',12*60*60);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
session_start();
session_set_cookie_params(3600); // sessions last 1 hour
session_start(); // do this after setting the params
====
PDO
The
PHP Data Objects (
PDO) extension defines a lightweight, consistent interface
for accessing databases in PHP. Each database driver that
implements the PDO interface can expose database-specific
features as regular extension functions. Note that you cannot
perform any database functions using the PDO extension by
itself; you must use a
database-specific
PDO driver to access a database server.
PDO provides a
data-access abstraction layer, which
means that, regardless of which database you're using, you use the same
functions to issue queries and fetch data. PDO does
not provide a
database
abstraction; it doesn't rewrite SQL or emulate missing features. You
should use a full-blown abstraction layer if you need that facility.
PDO and ORM are two entirely different things.
PDO is a specific implementation of a Database Access Abstraction
Layer, it enables you to connect, run SQL and retrieve results from the
database with an API that is consistent across different database
backends (e.g. MySQL, PostgreSQL, MS SQL, etc.)
An ORM on the other hand is something more specialised: It's a
framework for mapping relational tables to application domain objects
and relationships between them. These are often built on top of DALs
like PDO.
To see the difference, consider having to retrieve an object or
record. With PDO, you'd need to write SQL for selecting the right row in
the right table, and have logic for extracting that row, and mapping
the fields to a PHP object's variables. You as the user have to take
care of all this.
On the other hand, with an ORM, you'd simply say: find me the Object X
by this ID, and the ORM would do its magic and give you that object,
without you having to write the SQL yourself.
===
Two MySQL timestamp columns in one table
Try this one to create your table:
CREATE TABLE IF NOT EXISTS db.test_table
(
Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
created DATETIME DEFAULT NULL,
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted TINYINT DEFAULT 0,
notes TEXT DEFAULT NULL,
description VARCHAR(100)
)
Note that
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
will allow to update this field automatically.
And set this one for a trigger before inserting records:
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
TRIGGER `db`.`on_before_insert` BEFORE INSERT
ON `db`.`test_table`
FOR EACH ROW BEGIN
SET new.created = NOW();
END$$
DELIMITER ;
Then you can use this to insert:
INSERT INTO db.test_table(description) VALUES ("Description")
and to update your record
UPDATE db.test_table SET description = "Description 2" where Id=1
And your created and updated fields will be set appropiately.
===
Use
$this to refer to the current
object. Use
self to refer to the
current class. In other words, use
$this->member for non-static members,
use
self::$member for static members.
===
Q: Jquery, selectors, attributes, html(),val(), ajax process
===
egex Validation - Use Alphanumeric As Well As Dash (-) Underscore (_)
echo preg_match('/^[a-zA-Z0-9]+$/',$text);
===