Compare two Date

var d1_str = "10-02-2010";

var d2_str = "11-01-2010";

var d1=0;


var d2=0;


d1 = new Date(d1_str.split('-')[2],d1_str.split('-')[1],d1_str.split('-')[0]);

d2 = new Date(d2_str.split('-')[2],d2_str.split('-')[1],d2_str.split('-')[0]);


if (d1.getTime()>d2.getTime()) {

alert("End Date should be greater than the Start date.");


return false;


}

else

{


return true;


}

Check Integer

function isInteger(s)
{
var i;
s = s.toString();
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (isNaN(c))
{
alert("Given value is not a number");
return false;
}
}
return true;
}

Searching for a email or word inside a text string

$main_string_new="a@gmail.com,yug@gmail.com,a@gmail.com";

if(stristr($main_string_new,"a@gmail.com,")){

echo "String contains a Email id
'a@gmail.com' ";
}
else {
echo "String does not contains a email id '
a@gmail.com' ";
}

Remove Duplicate words in javascript

<SCRIPT LANGUAGE="Javascript">
<!--
function remove_list()
{
var count = 0;
var list = document.form1.list.value;
list =list.replace(/\r/gi, "\n");
list = list.replace(/\n+/gi, "\n");

var listvalues = new Array();
var newlist = new Array();

listvalues = list.split("\n");

var hash = new Object();

for (var i=0; i<listvalues.length; i++)
{
if (hash[listvalues[i].toLowerCase()] != 1)
{
newlist = newlist.concat(listvalues[i]);
hash[listvalues[i].toLowerCase()] = 1
}
else { count++; }
}
document.form1.list.value = newlist.join("\r\n");

}
//-->
</SCRIPT>

</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document -->

<BODY>

<CENTER>
<FORM ACTION="" NAME="form1" ID="form1">
<TABLE BORDER=1 CELLPADDING=5 BORDERCOLOR="#FF0000" BGCOLOR="#FFFFFF">
<TR>
<TD>Paste list to be de-duped here<BR>(one value per line)<P><TEXTAREA NAME="mainlist" COLS=30 ROWS=20></TEXTAREA></TD>
</TR>
<TR><TD align="center"><input type="button" onClick="remove_list();" value="De-Dupe List!"></TD></TR>
</TABLE>
</center>
</FORM>

For Example -:
Input-: Apple,Mango,Apple,Orange

Output -: Apple,Mango,Orange


MySQL Triggers

Introduction to SQL Triggers

SQL trigger is an SQL statements or a set of SQL statements which is stored to be activated or fired when an event associating with a database table occurs. The event can be any event including INSERT, UPDATE and DELETE.
Sometimes a trigger is referred as a special kind of stored procedure in term of procedural code inside its body. The difference between a trigger and a stored procedure is that a trigger is activated or called when an event happens in a database table, a stored procedure must be called explicitly. For example you can have some business logic to do before or after inserting a new record in a database table.

Before applying trigger in your database project, you should know its pros and cons to use it properly.

Advantages of using SQL trigger

  • SQL Trigger provides an alternative way to check integrity.
  • SQL trigger can catch the errors in business logic in the database level.
  • SQL trigger provides an alternative way to run scheduled tasks. With SQL trigger, you don’t have to wait to run the scheduled tasks. You can handle those tasks before or after changes being made to database tables.
  • SQL trigger is very useful when you use it to audit the changes of data in a database table.

Disadvantages of using SQL trigger

  • SQL trigger only can provide extended validation and cannot replace all the validations. Some simple validations can be done in the application level. For example, you can validate input check in the client side by using javascript or in the server side by server script using PHP or ASP.NET.
  • SQL Triggers executes invisibly from client-application which connects to the database server so it is difficult to figure out what happen underlying database layer.
  • SQL Triggers run every updates made to the table therefore it adds workload to the database and cause system runs slower.

Triggers or stored procedures? It depends on the the situation but it is practical that if you have no way to get the work done with stored procedure, think abouttriggers.

Create the First Trigger in MySQL

Let’s start creating the first trigger in MySQL by following a simple scenario. In the sample database, we have employees table as follows:
Each time a employee wants change his/her last name, you want to keep track all of changes in another table. In order to do so you can create a new table called employees_audit to keep track the changes.

 CREATE TABLE employees_audit ( 
id int(11) NOT NULL AUTO_INCREMENT,
employeeNumber int(11) NOT NULL,
lastname varchar(50) NOT NULL,
changedon datetime DEFAULT NULL,
action varchar(50) DEFAULT NULL,
PRIMARY KEY (id)
)

In order to keep track the changes of last name of employee we can create a trigger that is fired before we make any update on the employees table. Here is the source code of the trigger

 DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedon = NOW(); END$$
DELIMITER ;

Now you can test the trigger you’ve created by updating last name of any employee in employees table. Suppose we update last name of employee which has employee number is 3:

 UPDATE employees
SET lastName = 'Phan'
WHERE employeeNumber = 1056

Now when you can see the changes audited automatically in the employees_audit table by executing the following query

 SELECT *
FROM employees_audit

In order to create a trigger you use the following syntax:

 CREATE TRIGGER trigger_name trigger_time trigger_event
ON table_name
FOR EACH ROW
BEGIN
...
END
  • CREATE TRIGGER statement is used to create triggers.
  • The trigger name should follow the naming convention [trigger time]_[table name]_[trigger event], for example before_employees_update
  • Trigger activation time can be BEFORE or AFTER. You must specify the activation time when you define a trigger. You use BEFORE when you want to process action prior to the change being made in the table and AFTER if you need to process action after changes are made.
  • Trigger event can be INSERT, UPDATE and DELETE. These events cause trigger to fire and process logic inside trigger body. A trigger only can fire with one event. To define trigger which are fired by multiple events, you have to define multiple triggers, one for each event. Be noted that any SQL statements make update data in database table will cause trigger to fire. For example, LOAD DATA statement insert records into a table will also cause the trigger associated with that table to fire.
  • A trigger must be associated with a specific table. Without a table trigger does not exist so you have to specify the table name after the ON keyword.
  • You can write the logic between BEGIN and END block of the trigger.
  • MySQL gives you OLD and NEW keyword to help you write trigger more efficient. The OLD keyword refers to the existing row before you update data and the NEW keyword refers to the new row after you update data.

In this tutorial, you have learnt how to create the first trigger. In this example, you wrote the first trigger to audit changes oflast name of employee in employees table.



MySQL 5.0 New Features: Stored Procedures

A Definition and an Example

A stored procedure is a procedure (like a subprogram in a regular computing language) that is stored (in the database). Correctly speaking, MySQL supports "routines" and there are two kinds of routines: stored procedures which you call, or functions whose return values you use in other SQL statements the same way that you use pre-installed MySQL functions like pi(). I'll use the word "stored procedures" more frequently than "routines" because it's what we've used in the past, and what people expect us to use.

A stored procedure has a name, a parameter list, and an SQL statement, which can contain many more SQL statements. There is new syntax for local variables, error handling, loop control, and IF conditions. Here is an example of a statement that creates a stored procedure.

CREATE PROCEDURE procedure1                /* name */

(IN parameter1 INTEGER) /* parameters */

BEGIN /* start of block */

DECLARE variable1 CHAR(10); /* variables */

IF parameter1 = 17 THEN /* start of IF */

SET variable1 = 'birds'; /* assignment */

Else

SET variable1 = 'beasts'; /* assignment */

END IF;
/* end of IF */

INSERT INTO table1 VALUES (variable1);
/* statement */

END
/* end of block */

What I'm going to do is explain in detail all the things you can do with stored procedures. We'll also get into another new database object, triggers, because there is a tendency to associate triggers with stored procedures.

Why Stored Procedures

Stored procedures are something new for MySQL, so naturally you'll approach them with some caution. After all, there's no track record, no large body of user experience that proves they're the way to go. Nevertheless, you should start to think now about moving your code out of where it is now (an application host program, a UDF, a script), and into a stored procedure. The reasons for using procedures are compelling.

Stored procedures are proven technology! Yes, they are new in MySQL, but the same functionality exists in other DBMSs, and often precisely the same syntax too. So there are concepts that you can steal, there are people with experience whom you can consult or hire, there is third-party documentation (books or web pages) that you can read.

Stored procedures are fast! Well, we can't prove that for MySQL yet, and everyone's experience will vary. What we can say is that the MySQL server takes some advantage of caching, just as prepared statements do. There is no compilation, so an SQL stored procedure won't work as quickly as a procedure written with an external language such as C. The main speed gain comes from reduction of network traffic. If you have a repetitive task that requires checking, looping, multiple statements, and no user interaction, do it with a single call to a procedure that's stored on the server. Then there won't be messages going back and forth between server and client, for every step of the task.

Stored procedures are components! Suppose that you change your host language -- no problem, the logic is in the database not the application.

Stored procedures are portable! When you write your stored procedure in SQL, you know that it will run on every platform that MySQL runs on, without obliging you to install an additional runtime-environment package, or set permissions for program execution in the operating system, or deploy different packages if you have different computer types. That's the advantage of writing in SQL rather than in an external language like Java or C or PHP. Don't get me wrong about this: I know there are sometimes excellent reasons to support external-language routines, they just lack this particular advantage.

Stored procedures are stored! If you write a procedure with the right naming conventions, for example saying chequing_withdrawal for a bank transaction, then people who want to know about chequing can find your procedure. It's always available as 'source code' in the database itself. And it makes sense to link the data with the processes that operate on the data, as you might have heard in your programming-theory classes.

Stored procedures are migratory! MySQL adheres fairly closely to the SQL:2003 standard. Others (DB2, Mimer) also adhere. Others (Oracle, SQL Server) don't adhere but I'll be providing tips and tools that make it easier to take code written for another DBMS and plunking it into MySQL.

My SQL Interview Questions and Answers

What's MySQL ?
MySQL (pronounced "my ess cue el") is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. MySQL is noted mainly for its speed, reliability, and flexibility. ...

What is DDL, DML and DCL ?
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 get the number of rows affected by query?
SELECT COUNT (user_id) FROM users would only return the number of user_id’s।


If the value in the column is repeatable, how do you find out the unique values?
Use DISTINCT in the query, such as SELECT DISTINCT user_firstname FROM users; You can also ask for a number of distinct values by saying
"SELECT COUNT (DISTINCT user_firstname) FROM users; "

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);

What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) ?
It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id

How do you find out which auto increment was assigned on the last insert?

SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.

What does –i-am-a-dummy flag to do when starting MySQL?
Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.


On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do?
What it means is that so of the data that you’re trying to delete is still alive in another table. Like if you have a table for universities and a table for students, which contains the ID of the university they go to, running a delete on a university table will fail if the students table still contains people enrolled at that university. Proper way to do it would be to delete the offending data first, and then delete the university in question. Quick way would involve running SET foreign_key_checks=0 before the DELETE command, and setting the parameter back to 1 after the DELETE is done. If your foreign key was formulated with ON DELETE CASCADE, the data in dependent tables will be removed automatically.

When would you use ORDER BY in DELETE statement?
When you’re not deleting by row ID. Such as in DELETE FROM techpreparation_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techpreparation_com_questions.

How can you see all indexes defined for a table?
SHOW INDEX FROM techpreparation_questions;

How would you change a column from VARCHAR(10) to VARCHAR(50)?
ALTER TABLE techpreparation_questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50).

How would you delete a column?
ALTER TABLE techpreparation_answers DROP answer_user_id।

How would you change a table to InnoDB?
ALTER TABLE techpreparation_questions ENGINE innodb;

How do I find out all databases starting with ‘tech’ to which I have access to?
SHOW DATABASES LIKE ‘tech%’;

How do you concatenate strings in MySQL?
CONCAT (string1, string2, string3)

What’s the difference between CHAR_LENGTH and LENGTH?
The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.

How do you convert a string to UTF-8?

SELECT (techpreparation_question USING utf8);

What do % and _ mean inside LIKE statement?
% corresponds to 0 or more characters, _ is exactly one character.

What does + mean in REGEXP?
At least one character. Appendix G. Regular Expressions from MySQL manual is worth perusing before the interview.

How do you get the month from a timestamp?
SELECT MONTH(techpreparation_timestamp) from techpreparation_questions;

How do you offload the time/date handling to MySQL?
SELECT DATE_FORMAT(techpreparation_timestamp, ‘%Y-%m-%d’) from techpreparation_questions; A similar TIME_FORMAT function deals with time.

How do you add three minutes to a date?
ADDDATE(techpreparation_publication_date, INTERVAL 3 MINUTE)

What’s the difference between Unix timestamps and MySQL timestamps?
Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format.

How do you convert between Unix timestamps and MySQL timestamps?
UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp।

Explain the difference between mysql and mysql interfaces in PHP?
mysqli is the object-oriented version of mysql library functions.

What’s the default port for MySQL Server?
3306

How do you change a password for an existing user via mysqladmin?
mysqladmin -u root -p password "newpassword"

Use mysqldump to create a copy of the database?
mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql

Explain advantages of InnoDB over MyISAM?
Row-level locking, transactions, foreign key constraints and crash recovery.

Explain advantages of MyISAM over InnoDB?
MyISAM and InnoDB are storage engines in MySql।MyISAM does not support transactions while InnoDB support it।

What happens if a table has one column defined as TIMESTAMP?
That field gets the current timestamp whenever the row gets altered.

But what if you really want to store the timestamp data, such as the publication date of the article?
Create two columns of type TIMESTAMP and use the second one for your real data

Php interview Questions

Q:1 How can we submit a form without a submit button?

A:1 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).

Q:2 In how many ways we can retrieve the data in the result set of MySQL using PHP?

A:2 You can do it by 4 Ways
1. mysql_fetch_row.

2. mysql_fetch_array

3. mysql_fetch_object

4. mysql_fetch_assoc

Q:3 What is the difference between mysql_fetch_object and mysql_fetch_array?

A:3 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).

Q:4 What is the difference between $message and $$message?
A:4 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.

Q:5 How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’ using regular expression of PHP?

A:5 preg_match(”/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);

echo $found[1];

Q:6 How can we create a database using PHP and MySQL?

A:6 We can create MySQL database with the use of

mysql_create_db(“Database Name”)

Q:7 What are the differences between require and include, include_once and require_once?

A:7 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 handlefailure. include() produces a Warning while require() results in a Fatal Error. In other words, use require() if you want a missingfile 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 differencebeing 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 particularexecution 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.

Q:8 Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?

A:8 Yes we can use include() more than one time in any page though it is not a very good practice.


Q:9What are the different tables present in MySQL, which type of table is generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ?

A:9 Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM

MyISAM is the default storage engine as of MySQL 3.23 and as a result if we do not specify the table name explicitly it will be assigned to the default engine.

Q:10 How can we encrypt the username and password using PHP?
A:10 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()

Change a string link to URL

$string = trim(addslashes($_REQUEST['question']));
$ques = make_clickable($string);

function _make_url_clickable_cb($matches) {
$ret = '';
$url = $matches[2];

if ( empty($url) )
return $matches[0];
// removed trailing [.,;:] from URL
if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
return $matches[1] . "$url" . $ret;
}

function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;

if ( empty($dest) )
return $matches[0];
// removed trailing [,;:] from URL
if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
return $matches[1] . "$dest" . $ret;
}

function _make_email_clickable_cb($matches) {
$email = $matches[2] . '@' . $matches[3];
return $matches[1] . "$email";
}

function make_clickable($ret) {
$ret = ' ' . $ret;
// in testing, using arrays here was found to be faster
$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);

// this one is not in an array because we need it to run last, for cleanup of accidental links within links
$ret = preg_replace("#(]+?>|>))]+?>([^>]+?)#i", "$1$3", $ret);
$ret = trim($ret);
return $ret;
}