How do you find the Second highest Salary?

SELECT MAX( E1.salary ) FROM employee E1, employee E2 WHERE E1.salary < E2.salary

Multiple select and delete

JAVASCRIPT code
———————-

<script language=’javascript’  type=’text/type’>
function checkUncheckAll(form)
{
var selectall = form.selectall;
for ( var i=0; i < form.elements.length; i++ )
{
var e = form.elements[i];
if (selectall.checked)
{
e.checked = true;
}
else
{
e.checked = false;
}
}
}

</script>

PHP code
—————–

<?php

if(count($_POST)>0 && $_REQUEST['deleteall']==”Delete”)
{
$cnt=count($_REQUEST['chkmem']);
$chkmem=$_REQUEST['chkmem'];
for($i=0;$i<$cnt;$i++)
{
mysql_query(“delete from tbl_name where sid=”.$chkmem[$i]) or die(mysql_error());
}
}

?>

HTML code
————-
<form name=”frmSettings” action=”" method=”post”>
<input type=”submit” name=”deleteall” value=”Delete” onClick=”return confirm(‘Are you sure?’);” style=”width:60px;”>
</form>

Arrange order or sorting the listing

The PHP Code
——————

// if an arrow link was clicked…
if ($_GET['dir'] && $_GET['id']) {
// make GET vars easier to handle
$dir = $_GET['dir'];
// cast as int and couple with switch for sql injection prevention for $id
$id = (int) $_GET['id'];
// decide what row we’re swapping based on $dir
switch ($dir) {
// if we’re going up, swap is 1 less than id
case ‘up’:
// make sure that there’s a row above to swap
$swap = ($id > 1)? $id– : 1;
break;
// if we’re going down, swap is 1 more than id
case ‘down’:
// find out what the highest row is
$sql = “SELECT count(*) FROM tbl_name”;
$resultusort = mysql_query($sql) or die(mysql_error());
$r = mysql_fetch_row($resultusort);
$max = $r[0];
// make sure that there’s a row below to swap with
$swap = ($id < $max)? $id++ : $max;
break;
// default value (sql injection prevention for $dir)
default:
$swap = $id;
} // end switch $dir
// swap the rows. Basic idea is to make $id=$swap and $swap=$id
$sql = “UPDATE tbl_name SET usort = CASE usort WHEN $id THEN $swap WHEN $swap THEN $id END WHERE usort IN ($id, $swap)”;
$resultupdateusort = mysql_query($sql) or die(mysql_error());
} // end if GET

HTML code
—————

<td align=”center” valign=”middle” bgcolor=”#FFFFFF”>

<a href=”index.php?action=gallerylist&task=list&dir=up&id=<?php echo $aRow['usort'];?>”><img src=”arrange_up.gif” alt=”Up” width=”36″ height=”30″ border=”0″ /></a>
<a href=”index.php?action=gallerylist&task=list&dir=down&id=<?php echo $aRow['usort'];?>”><img src=”arrange_down.gif” alt=”Down” width=”36″ height=”30″ border=”0″ /></a>
</td>

Modify or Remove a Session

<?php
// you have to open the session to be able to modify or remove it
session_start();

// to change a variable, just overwrite it
$_SESSION['size']=’large’;

//you can remove a single variable in the session
unset($_SESSION['shape']);

// or this would remove all the variables in the session, but not the session itself
session_unset();

// this would destroy the session variables
session_destroy();
?>
The code above demonstrates how to edit or remove individual session variables, or the entire session. To change a session variable we just reset it to something else. We can use unset() to remove a single variable, or session_unset() to remove all variables for a session. We can also use session_destroy() to destroy the session completely. By default a session lasts until the user closes their browser. This can be changed in the php.ini file by change the 0 in session.cookie_lifetime = 0 to be the number of seconds you want the session to last, or by using session_set_cookie_params().

Sending Email (Text/HTML/Attachments)

<?php
require_once(‘class.mail.php’);  //MAIL CLASS

$filename     = $HTTP_POST_FILES['Filename']['name'];
$tempFilename     = $HTTP_POST_FILES['Filename']['tmp_name'];
$content_type = $HTTP_POST_FILES['Filename']['type'];
if(isset($filename)){
# read a JPEG picture from the disk

@$fd = fopen($tempFilename, “r”);

@$data = fread($fd, filesize($tempFilename));

@fclose($fd);
}

# create object instance
$mail = new MailAttach;

$to= ‘replyarya2u@gmail.com’;
$subject = ‘Test’;

# set all data slots
$mail->from    = ”;
$mail->to      = $to;
$mail->subject = $subject;
$mail->body    = “Plese find the attachment.”;

if($filename <> “”)
{
# append the attachment
$mail->add_attachment($data, $filename, $content_type);
}

# send e-mail
$enviado = $mail->send();
?>

class.mail.php  //MAIL CLASS

<?php
class MailAttach
{
var $parts;
var $to;
var $from;
var $headers;
var $subject;
var $body;

/*
*     void MailAttach()
*     class constructor
*/

function MailAttach() {
$this->parts = array();
$this->to =  “”;
$this->from =  “”;
$this->subject =  “”;
$this->body =  “”;
$this->headers =  “”;
}

/*
*     void add_attachment(string message, [string name], [string ctype])
*     Add an attachment to the mail object
*/

function add_attachment($message, $name =  “”, $ctype = “application/octet-stream”) {

$this->parts[] = array (

“ctype” => $ctype,

“message” => $message,

“encode” => $encode,

“name” => $name

);

}

/*
*      void build_message(array part=
*      Build message parts of an multipart mail
*/

function build_message($part) {
$message = $part[ "message"];
$message = chunk_split(base64_encode($message));

$encoding =  “base64″;
return  “Content-Type: “.$part[ "ctype"].
($part[ "name"]? “; name = \”".$part[ "name"].
“\”" :  “”).

“\nContent-Transfer-Encoding: $encoding\n\n$message\n”;
}

/*
*      void build_multipart()
*      Build a multipart mail
*/

function build_multipart() {
$boundary =  “b”.md5(uniqid(time()));
$multipart =
“Content-Type: multipart/mixed; boundary = $boundary\n\nThis is a MIME encoded message.\n\n–$boundary”;

for($i = sizeof($this->parts)-1; $i >= 0; $i–)
{
$multipart .=  “\n”.$this->build_message($this->parts[$i]).
“–$boundary”;
}
return $multipart.=  “–\n”;
}

/*
*      string get_mail()
*      returns the constructed mail
*/

function get_mail($complete = true) {

$mime =  “”;

if (!empty($this->from))

$mime .=  “From: “.$this->from. “\n”;

if (!empty($this->headers))
$mime .= $this->headers. “\n”;

if ($complete) {
if (!empty($this->to)) {

$mime .= “To: $this->to\n”;
}

if (!empty($this->subject)) {
$mime .= “Subject: $this->subject\n”;
}
}

if (!empty($this->body))
$this->add_attachment($this->body,  “”,  “text/plain”);
$mime .=  “MIME-Version: 1.0\n”.$this->build_multipart();
return $mime;
}

/*
*      void send()
*      Send the mail (last class-function to be called)
*/

function send() {
$mime = $this->get_mail(false);
if (mail($this->to, $this->subject,  “”, $mime)) {
return true;
}else{
return false;
}

}

};
?>

Set session time

session_start(); //SESSION START

// set timeout period in seconds
$inactive = 600;

// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) )
{
$session_life = time() – $_SESSION['timeout'];
if($session_life > $inactive)
{
session_destroy();
header(“Location: login.php”);
}
}
$_SESSION['timeout'] = time();

Call parent window’s javascript function from child window OR passing data from child window to parent window in javascript

Hi, I was working on small application and I had a requirement as described here. I was creating a page in which user can add multiple cotact detail for him. The page has facility for add, delete and edit the contact. I was storing all these information in view state and finally on Save All button adding them to database. After the page is completed client has requested that user can have option to select contacts from database also. So I have to open a popup from which user can select multiple contacts and once user click on “Select” button on popup all the selected contacts should be available in grid on main page along with the contacts user has added manually.

To achieve this I need have added hidden field on parent page and on child page I access that hidden field to set the IDs of selected contacts. Once the selected IDs are available on parent window, I need to postback the page so that I can take all the data for those IDs from database and add it to grid for edit or save.

I was knowing that I can set “locationhref”  of parent window in child window and then close child window. However this will redirecr the parent page to new location (here new location is same page) but we loose viewstate data. This solution does not work in my case.

One of my friend suggested me two ways to solve my problem. First, I can call “Click” event of parent window’s button in child window so that parent window will post back and the code behind I had written for that button’s click had;ler will be executed. Yes this is possible !!   Second, I can call javascript function written on parent window from child window. This function use ajax and execute server side code once I get selected contact IDs in hidden field.

Lets implement First logic. Below is the javascript to raise button click event on parent window from child window.

// Set parent window’s hidden field value from child window
window.opener.document.getElementById(Client ID of Hidden Field).value = Selected IDs;

// raise button click event of parent window
window.opener.document.getElementById(Client ID Of Button).click();

// Close the child window
close();

Fig – (1) Javascript on child window to raise button click event on parent window

I had written this script on child page. Tis will raise button click event and in post back I wrote the logic of retrieving data from database for IDs set in hidden field and displayed them in grid.

Now the second way, call javascript function of parent window from child window.

<script language="Javascript" type="text/javascript">
    function CallAlert()
    {
        alert("This is parent window's alert function.");
    }
</script>

Fig – (2) Javascript on parent window.

<script language="Javascript" type="text/javascript">

    function SetParentWindowsHiddenFieldValue()
    {
        window.opener.document.getElementById("HiddenField1").value =
                            document.getElementById("TextBox1").value;
        return false;
    } 

    function CallParentWindowFunction()
    {
        window.opener.CallAlert();
        return false;
    }
</script>

Fig – (3) Javascript on child window.

Take two buttons on child window. Call “SetParentWindowsHiddenFieldValue” on click of one button and call “CallParentWindowFunction” on click of second button and see the result.

Happy Programming.

Convert array to comma separated string

$aSelectUserId = array(‘mango’, ’orange’, ’papaya’, ’apple’, ’pineapple’);
$sCommaAdded   = implode( “,”, $aSelectUserId );
echo $sCommaAdded;

//OUTPUT >>>mango,orange,papaya, apple,’pineapple

PHP Send Email Using Authenticated SMTP Mail Server In Real Time

PHP has mail() function to send an email to users. However this mail() will not work:

=> If sendmail (or compatible binary) is not installed

=> If Apache Web server / Lighttpd running in chrooted jail

=> And your smtp server needs an authentication before sending an email

=> Or you just need to send email using PHP PEAR

In all these cases you need to use PHP PEAR’s Mail:: interface. It defines the interface for implementing mailers under the PEAR hierarchy, and provides supporting functions which are useful in multiple mailer backends. In this tip you will learn about how to send an e-mail directly to client smtp server in real time.

PHP Pear’s Mail.php is located in /usr/share/pear/ directory. Following is sample code to send an email via authenticated smtp server.

PHP send email using PHP SMTP mail Pear functions – Sample source code

Following code is well commented, you need to make necessary changes as per your setup.

<?php
include("Mail.php");
/* mail setup recipients, subject etc */
$recipients = "feedback@yourdot.com";
$headers["From"] = "user@somewhere.com";
$headers["To"] = "feedback@yourdot.com";
$headers["Subject"] = "User feedback";
$mailmsg = "Hello, This is a test.";
/* SMTP server name, port, user/passwd */
$smtpinfo["host"] = "smtp.mycorp.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "smtpusername";
$smtpinfo["password"] = "smtpPassword";
/* Create the mail object using the Mail::factory method */
$mail_object =& Mail::factory("smtp", $smtpinfo);
/* Ok send mail */
$mail_object->send($recipients, $headers, $mailmsg);
?>

Popular Web Development Models (SDLC)

The following are some basic popular models that are adopted by many software development firms

A. System Development Life Cycle (SDLC) Model
B. Prototyping Model
C. Rapid Application Development Model
D. Component Assembly Model

A. System Development Life Cycle (SDLC) Model
This is also known as Classic Life Cycle Model (or) Linear Sequential Model (or) Waterfall Method. This model has the following activities.
1. System/Information Engineering and Modeling As software is always of a large system (or business), work begins by establishing the requirements for all system elements and then allocating some subset of these requirements to software. This system view is essential when the software must interface with other elements such as hardware, people and other resources. System is the basic and very critical requirement for the existence of software in any entity. So if the system is not in place, the system should be engineered and put in place. In some cases, to extract the maximum output, the system should be re-engineered and spruced up. Once the ideal system is engineered or tuned, the development team studies the software requirement for the system.
2. Software Requirement Analysis This process is also known as feasibility study. In this phase, the development team visits the customer and studies their system. They investigate the need for possible software automation in the given system. By the end of the feasibility study, the team furnishes a document that holds the different specific recommendations for the candidate system. It also includes the personnel assignments, costs, project schedule, target dates etc…. The requirement gathering process is intensified and focused specially on software. To understand the nature of the program(s) to be built, the system engineer or “Analyst” must understand the information domain for the software, as well as required function, behavior, performance and interfacing. The essential purpose of this phase is to find the need and to define the problem that needs to be solved .
3. System Analysis and Design In this phase, the software development process, the software’s overall structure and its nuances are defined. In terms of the client/server technology, the number of tiers needed for the package architecture, the database design, the data structure design etc… are all defined in this phase. A software development model is thus created. Analysis and Design are very crucial in the whole development cycle. Any glitch in the design phase could be very expensive to solve in the later stage of the software development. Much care is taken during this phase. The logical system of the product is developed in this phase.
4. Code Generation The design must be translated into a machine-readable form. The code generation step performs this task. If the design is performed in a detailed manner, code generation can be accomplished without much complication. Programming tools like compilers, interpreters, debuggers etc… are used to generate the code. Different high level programming languages like C, C++, Pascal, Java are used for coding. With respect to the type of application, the right programming language is chosen.
5. Testing Once the code is generated, the software program testing begins. Different testing methodologies are available to unravel the bugs that were committed during the previous phases. Different testing tools and methodologies are already available. Some companies build their own testing tools that are tailor made for their own development operations.
6. Maintenance The software will definitely undergo change once it is delivered to the customer. There can be many reasons for this change to occur. Change could happen because of some unexpected input values into the system. In addition, the changes in the system could directly affect the software operations. The software should be developed to accommodate changes that could happen during the post implementation period.

B. Prototyping Model
This is a cyclic version of the linear model. In this model, once the requirement analysis is done and the design for a prototype is made, the development process gets started. Once the prototype is created, it is given to the customer for evaluation. The customer tests the package and gives his/her feed back to the developer who refines the product according to the customer’s exact expectation. After a finite number of iterations, the final software package is given to the customer. In this methodology, the software is evolved as a result of periodic shuttling of information between the customer and developer. This is the most popular development model in the contemporary IT industry. Most of the successful software products have been developed using this model – as it is very difficult (even for a whiz kid!) to comprehend all the requirements of a customer in one shot. There are many variations of this model skewed with respect to the project management styles of the companies. New versions of a software product evolve as a result of prototyping.

C. Rapid Application Development (RAD) Model
The RAD modelis a linear sequential software development process that emphasizes an extremely short development cycle. The RAD model is a “high speed” adaptation of the linear sequential model in which rapid development is achieved by using a component-based construction approach. Used primarily for information systems applications, the RAD approach encompasses the following phases: 1. Business modeling The information flow among business functions is modeled in a way that answers the following
questions: What information drives the business process?
What information is generated?
Who generates it?
Where does the information go?
Who processes it?
2. Data modeling The information flow defined as part of the business modeling phase is refined into a set of data objects that are needed to support the business. The characteristic (called attributes) of each object is identified and the relationships between these objects are defined.
3. Process modeling The data objects defined in the data-modeling phase are transformed to achieve the information flow necessary to implement a business function. Processing the descriptions are created for adding, modifying, deleting, or retrieving a data object.
4. Application generation The RAD model assumes the use of the RAD tools like VB, VC++, Delphi etc… rather than creating software using conventional third generation programming languages. The RAD model works to reuse existing program components (when possible) or create reusable components (when necessary). In all cases, automated tools are used to facilitate construction of the software.
5. Testing and turnover Since the RAD process emphasizes reuse, many of the program components have already been tested. This minimizes the testing and development time.

D. Component Assembly Model
Object technologies provide the technical framework for a component-based process model for software engineering. The object oriented paradigm emphasizes the creation of classes that encapsulate both data and the algorithm that are used to manipulate the data. If properly designed and implemented, object oriented classes are reusable across different applicationsand computer based system architectures. Component Assembly Model leads to software reusability. The integration/assembly of the already existing software components accelerate the development process. Nowadays many component libraries are available on the Internet. If the right components are chosen, the integration aspect is made much simpler.