What is array and how many type of array?

An array is a way of holding multiple closely-related values, such as the test scores of all students in a class. An array is made up of a key and a value, and the key points to the value.

There are two types of arrays: Indexed array and Associative array. Their difference is in the way the key is specified. Let’s look at both of them:

Indexed Array

In an indexed array, the keys are numeric and starts with 0, and the values can be any data type. The following shows two ways of assigning values to an indexed array:

$friends = array(“Sophie”,”Stella”,”Alice”);

This is equivalent to the following:

$friends[0] = “Sophie”;
$friends[1] = “Stella”;
$friends[2] = “Alice”;

Associative Array

In an associative array, the keys are not necessarily numeric, and even when they are numeric, not necessarily in any order. So, when you are putting data into an associative array, you’ll need to make sure you specify both the key and the value:

$student_score = array(“John”=>80, “Matt”=>90, “May”=>85);

This is equivalent to the following:

$student_score["John"] = 80;
$student_score["Matt"] = 90;
$student_score["May"] = 85;

Multidimensional Array

The arrays in the examples above are 1-dimensional. However, there will be times when multidimensional arrays are desired. What’s a multidimensional array? That’s when you have arrays of arrays. Let’s look at an example below:

$array1 = array (10,15,20);
$array2 = array (110,115,120);
$array3 = array (210,215,220);
$big_array = array ($array1, $array2, $array3);

$big_array is now a 2-dimensional array. For example, if you have the following output code:

print {$big_array[1,2]};

The output would be  120

Remember to use { } when you are accessing the value of a multidimensional array.

What does === do? What’s an example of something that will give true for ‘==’, but not ‘===’?

“====” means first check the condition & if it return true then assign that value against a variable.

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