Home|About|Documents | Cool Stuff |Links|Contact|
Cool Code that I wrote for my projects ...

 

The code to do date comparison Version 1
Date comparison Version 2
Email with various options ...
Array Sorting code...
Download with date wise sorting of the documents
C# using custom color for a row based on column color
Intersection of two arrays when comparison is based on only 1 key

The code to do date comparison Version 1 -

//this function compares any date to current date and returns results in form of integers
function date_compare ( $b_year, $b_month, $b_day )
{
$today = getdate();
$a_year = $today["year"];
$a_month = $today["mon"];
$a_day = $today["mday"];
$final_result = 9; //set it to random right now
if($a_year < $b_year)
{
$final_result = 1; //the given year is greater then current year..so the date is in the future..
}//year greater
else if($a_year == $b_year) //the years are the same ..so check the month
{
if($a_month < $b_month)
{
$final_result = 2; //the given month is greater then current month so date is in the future
}//greater month check
else
if($a_month == $b_month)//same months ..so check dates
{
if($a_day < $b_day)
{
$final_result = 3; //the given date is greatter then current date...
}
else if($a_day == $b_day)
{
$final_result = 4; //the dates are identical too..so date1 becomes equal to date 2
}
else
{
$final_result = -3; //the date1 < $date 2
}
}//equal month check
else
{
$final_result = -2;
}//month1 < month2
}//year same
else
{
$final_result = -1; //the year 1 is smaller then year 2 ..hence date1 < date2
}
return $final_result;
}

Date comparison Version 2

PHP lets you convert string into time and the time is in seconds ...so simple method to compare dates would be convert them into seconds and then substract them to find out the values.....Here is an example where I used it....

function getQuarter($recordDate, $current_year)
{
$quarterDecided = 0;
$next_year = $current_year; //since fiscal year 2006 means july 2005 to june 2006
$current_year = $current_year-1;
$date_2 = strtotime($recordDate);
//quarter 1
$date_1 = '7/1/'.$current_year;
$ts1_s = strtotime($date_1) - $date_2;
$date_1 = '9/30/'.$current_year;
$ts1_e = strtotime($date_1) - $date_2;

//quarter 2
$date_1 = '10/1/'.$current_year;
$ts2_s = strtotime($date_1) - $date_2;
$date_1 = '12/31/'.$current_year;
$ts2_e = strtotime($date_1) - $date_2;

//quarter 3
$date_1 = '1/1/'.$next_year;
$ts3_s = strtotime($date_1) - $date_2;
$date_1 = '3/30/'.$next_year;
$ts3_e = strtotime($date_1) - $date_2;

//quarter 4
$date_1 = '4/1/'.$next_year;
$ts4_s = strtotime($date_1) - $date_2;
$date_1 = '6/30/'.$next_year;
$ts4_e = strtotime($date_1) - $date_2;

if(($ts1_s<=0)&&($ts1_e>=0))
{
// print "<br>quarter 1 when date is ".$recordDate;
$quarterDecided = 1;
}
else
if(($ts2_s<=0)&&($ts2_e>=0))
{
// print "<br>quarter 2 when date is ".$recordDate;
$quarterDecided = 2;
}
else
if(($ts3_s<=0)&&($ts3_e>=0))
{
// print "<br>quarter 3 when date is ".$recordDate;
$quarterDecided = 3;
}
else
if(($ts4_s<=0)&&($ts4_e>=0))
{
// print "<br>quarter 4 when date is ".$recordDate;
$quarterDecided = 4;
}
return $quarterDecided;
}

Email with various options ...

This code was written to send email to Gamma Phi members based on various conditions... - http://www.exu.ilstu.edu/gamma_phi/admin/admin.phtml?file=e-mail.inc
<?
//--Written August 2005 by Abhilasha Sharma
//--EXU - Illinois State Extended University
//--Email Application for the gamma_phi website...
?>
<!--*************************************************************************************************************-->
<!--*************************************************************************************************************-->
<!--*************************************************************************************************************-->
<!--Pop Up for the help window...-->
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=500,left = 600,top = 100');");
}
// End -->
</script>

<!--*****Content Section*****-->
<?

//the function where the actual mail sending is occuring
function deliver_mail($member_set, $message, $subject , $first_name, $last_name, $headers)
{
print "<h3>Mail was successfully sent to the following people :- </h3>";

$count_member=count($member_set);
$from = "gamma_phi_circus@ilstu.edu";
for($i=0;$i<$count_member;$i++)
{
if($member_set[$i][1]==$_SESSION['name'])
{
$from = $member_set[$i][0];
}//from
}
for($i=0;$i<$count_member;$i++)
{
$to =$member_set[$i][0];
if(($to!="")&&($to!=" ")&&($to!="ajlight@ilstu.edu")&&($to!="jabinni@ilstu.edu"))//make sure duplicate copies dont go to the administrators ...just better they donno twice
{
$name = $member_set[$i][2]." ".$member_set[$i][3];
$message1 = "Dear ".$name.",\n\n".$message;
$ok = @mail($to, $subject, $message1, $headers);
Print ($i+1).".) ".$member_set[$i][2]." , ".$member_set[$i][3]."<br>";
}
}//member email loop

$to = "ajlight@ilstu.edu, jabinni@ilstu.edu, asharm4@ilstu.edu";
$subject = "Copy of the email sent on Gamma Phi Website with subject - ".$subject;
$ok = @mail($to, $subject, $message, $headers);
}

//this is special processing for the select member mailing option

if($selectmember==1)
{
$member_data_query = "SELECT email,login, lname, fname from member where email <> '' order by lname";
$member_data = retrieval_data_method($member_data_query);
$count_member=count($member_data);

$to = " ";
$from = 'gamma_phi_circus@ilstu.edu';

for($i=0;$i<$count_member;$i++)
{
if($member_data[$i][1]==$_SESSION['name'])
{
$from = $member_data[$i][0];
}//from
}

print "The mail sent successfully from the address ".$from." to the following members :- ";
$count = 0;

for($i=0;$i<$count_member;$i++)
{
$temp = ${"member".$i};
if(($temp != NULL)&&($member_data[$i][0]!="ajlight@ilstu.edu")&&($member_data[$i][0]!="jabinni@ilstu.edu")&&($member_data[$i][0]!="asharm4@ilstu.edu"))
{
$to= $member_data[$i][0];
mail ("$to", "$subject", "$message \n \n Thanks, $first_name $last_name \n \n","From: $from", $headers);
$array_name[$count] = $member_data[$i][2]." , ".$member_data[$i][3];
$count ++;
}//if NULL
}
for($k=0;$k<$count;$k++)
print "<br>".$array_name[$k];
print "<h3>Reminder<br>Any attachments cannot be sent using the select member option in this system.</h3>";


$to = "ajlight@ilstu.edu, jabinni@ilstu.edu, asharm4@ilstu.edu";
$subject = "Copy of the email sent on Gamma Phi Website with subject ".$subject;
mail ("$to", "$subject", "$message \n \n Thanks, $first_name $last_name \n \n","From: $from", $headers);
}
else if($sendmail)
{

/*cleaning up the message and subject*/
$message = str_replace("\'",' ',$message);
$message = str_replace("\"",' ',$message);
$message = str_replace("\\",' ',$message);
$message1 = $message;
$message = $message."\n\nThanks\n".$first_name." ".$last_name;

$subject = str_replace("\'",' ',$subject);
$subject = str_replace("\"",' ',$subject);
$subject = str_replace("\\",' ',$subject);

// Read POST request params into global vars
// Obtain file upload vars
$fileatt = $_FILES['fileatt']['tmp_name'];
$fileatt_type = $_FILES['fileatt']['type'];
$fileatt_name = $_FILES['fileatt']['name'];

$member_data_query = "SELECT email, login, lname, fname from member order by lname";
$member_set = retrieval_data_method($member_data_query);
$count_member = count($member_set);

$from = "";
for($i=0;$i<$count_member;$i++)
{
if($member_set[$i][1]==$_SESSION['name'])
{
$from = $member_set[$i][0];
}//from
}

$headers = "From: $from";

if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// Add the headers for a file attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

// Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";

// Base64 encode the file data
$data = chunk_split(base64_encode($data));

// Add file attachment to the message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
}//for file upload

/*Function to mail to only the admin members of the website*/
if(($sendtype!=4))
{
print $sendtype."Is here";
if($sendtype==0)
{
print "The mail was successfully sent to all the members with the valid email address in the gamma phi website.";
$member_data_query = "SELECT email, login, lname, fname from member order by lname";
}//all members
else
if($sendtype==1)
{
print "The mail was successfully sent to the administrators for the gamma phi website :-";
$member_data_query = "SELECT email, login, lname, fname from member where admin = 1 order by lname";
}//all admins
else
if($sendtype==2)
{
print "The mail was successfully sent to all the recording secretories with the valid email address in the gamma phi website.";
$member_data_query = "SELECT email, login, lname, fname from member where admin = 2 order by lname";
}//all rss
else
if($sendtype==3)
{
print "The mail was successfully sent to all the regular members with the valid email address in the gamma phi website.";
$member_data_query = "SELECT email, login, lname, fname from member where admin = 0 order by lname";
}//all regulars
else
if($sendtype==5)
{
print "The mail was successfully sent to all the active members with the valid email address in the gamma phi website.";
$member_data_query = "SELECT email, login, lname, fname from member where active_member='1' order by lname";
} //all active members
else
{
print "The mail was successfully sent to all the prospective members with the valid email address in the gamma phi website.";
$member_data_query = "SELECT email, login, lname, fname from member where active_member='2' order by lname";
}//all prospective members
$member_data = retrieval_data_method($member_data_query);
deliver_mail($member_data,$message,$subject, $first_name, $last_name, $headers);
}
else
{
$member_data_query = "SELECT email, login, lname, fname from member where email <> '' order by lname";
$member_data = retrieval_data_method($member_data_query);
$count_member = count($member_data);

print "<form action='member.phtml?file=e-mail_member.inc&selectmember=1' method='POST' enctype='multipart/form-data'>";
print "<table class='copysm'>";
print "<tr><td colspan='4'><b>Please choose the names of the members to whom the mail is addressed</b><br></td></tr>";
print "<input type='hidden' name=message value='".$message1."'/>";
print "<input type='hidden' name=subject value='".$subject."'/>";
print "<input type='hidden' name='first_name' value =".$first_name.">";
print "<input type='hidden' name='last_name' value =".$last_name.">";
for($i=0;$i<$count_member;)
{
print "<tr>
<td>
".$member_data[$i][2].", ".$member_data[$i][3]."
</td>
<td>";
$temp = "member".$i;
$i++;
print "<INPUT TYPE=CHECKBOX NAME='".$temp."'>
</td>";
if($member_data[$i][0]!="")
{
print" <td>
".$member_data[$i][2].", ".$member_data[$i][3]."
</td>
<td>";
$temp = "member".$i;
$i++;
print "<INPUT TYPE=CHECKBOX NAME='".$temp."'>
</td>";
}

print "</tr>";
}
print" </table>";
print("<br> <input type='submit' name='button' value='Send Mail'>");
print "</form>";

}//select member query
}//sendmail if
else
{
$member_data_query = "SELECT email, login, lname, fname from member where login ='".$_SESSION["name"]."'";
$member_data = retrieval_data_method($member_data_query);
print "<form action='member.phtml?file=e-mail_member.inc&sendmail=1' method='POST' enctype='multipart/form-data'>";
$today = getdate();
$entry_date = $today["month"]." ".$today["mday"].", ".$today["year"];
print "<input type='hidden' name='first_name' value =".$member_data[0][3].">";
print "<input type='hidden' name='last_name' value =".$member_data[0][2].">";
print "<table width='100%' class='copysm' border=1 bgcolor ='#DEE3EF'><tr><td>";
print "<table width='100%' class='copysm' border=0 cellspanning='0' cellpadding='5'>
<tr>
<td colspan=2><b>Compose</b></td>
</tr>
<tr>
<td colspan=2 bgcolor ='#DEE3EF'><hr></td>
</tr>
<tr><td width='30%'>";
print "<b>Reply to : </b>";
print "</td><td>";
print $member_data[0][3]." ".$member_data[0][2];
print "</td></tr><tr><td>";
print "<b>Date : </b>";
print "</td><td>";
print $entry_date;
print "</td></tr><tr><td>";
print "<b>Recipient</b>";
print "</td><td>";
print" <select name=sendtype size='-1'>
<option value=0 SELECTED>All the members</option>
<option value=1>All the Administrators</option>
<option value=2>All the Recording Secretaries</option>
<option value=3>All the Regular Members</option>
<option value=5>All the Active Members</option>
<option value=6>All the Prospective Members</option>
<option value=4>Select Membes only</option>
</select>";
print "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"javascript:popUp('help/email_help.phtml');\" class=headlinks2><img src='images/help.gif' alt='help' height='25' border='0'>Help</a>";
print "</td></tr><tr><td>";
print "<b>Subject : </b>";
print "</td><td>";
print "<input type='text' name='subject' size='50'/>";
print "</td></tr><tr><td>";
print "<b>File Attachment : </b>";
print "</td><td>";
print "<input type='file' name='fileatt'/><br>";
print "</td></tr><tr><td colspan='2'>";
print "<h3>File Attachment option not available for <em>select member</em> mailing.</h3>";
print "</td></tr><tr><td colspan='2'>";
?> <textarea cols="55" rows="10" name="message" wrap=virtual><?print ""?></textarea><?
print "</td></tr><tr><td colspan='2'>";
print("<br> <input type='submit' name='button' value='Send Mail'>");
print "</td></tr></table>";//inside table
print "</td></tr></table>";//table 1 border table
print "</form>";
}//else for sendmail
?>
<!--*****Content Section ends here *****-->
</td>

</tr>
</table>

<?
include("../includes/address.phtml");
?>
</div>
</body>
</html>

Array Sorting code...

This code was written for RSP website because they wanted sorting of data in run time...So, here is the page that uses it..and the code - http://reports.rsp.ilstu.edu/container.phtml?file=type_of_grant&season=FY06&quarter=0&college=ALL
/********************************************************************************************
Set the different sort orders here */

if($orderby=='typeofgrant')
{
foreach($display_individual_record as $res)
$sortAux[] = $res[0];
}

if($orderby=='proposals')
{
foreach($display_individual_record as $res)
$sortAux[] = $res[1];
}

if($orderby=='requested')
{
foreach($display_individual_record as $res)
$sortAux[] = $res[2];
}

if($orderby=='awards')
{
foreach($display_individual_record as $res)
$sortAux[] = $res[3];
}

if($orderby=='recieved')
{
foreach($display_individual_record as $res)
$sortAux[] = $res[4];
}
if($order_dir==2)
{
array_multisort($sortAux, SORT_DESC, $display_individual_record);
$order_dir=1;
}
else if($order_dir==1)
{
array_multisort($sortAux, SORT_ASC, $display_individual_record);
$order_dir=2;
}


/********************************************************************************************/

Download with date wise sorting of the documents

I took the downloads function already present for the EU..(I think sharik wrote it...) and modified it to have the date wise sorting of the documents. Also, added the catch where the current working directory is computed at the run time as compared to hard coded one in the older code...
function list_download()
{

$retVal = array();
//set current working directory
$dirname = getcwd();
$dirname = $dirname."/download";
//Load Directory Into Array
$handle=opendir($dirname);
$i=0;
while ($file = readdir($handle))
if ($file != "." && $file != "..")
{
$retVal[$i][0] = $file;
$retVal[$i][1] = date ("Y m d", filemtime($dirname."/".$file));
$i++;
}
//Clean up and sort
closedir($handle);
return $retVal;

} //--End list_downloads function

C# using custom color for a row based on column color

Step 1 -- make yourself a datagrid

<asp:DataGrid id="DataGrid1" AutoGenerateColumns =false style="Z-INDEX: 101; LEFT: 18px; POSITION: absolute; TOP: 18px" runat="server">
<Columns> <asp:TemplateColumn > <HeaderTemplate >
<table border=0 width="100%">
<tr>
<td>ProductID
<td>ProductName
<td>UnitPrice
</HeaderTemplate>
<ItemTemplate >
<tr>
<td><%#DataBinder.Eval(Container.DataItem , "ProductID")%>
<td><%#DataBinder.Eval(Container.DataItem , "ProductName")%>
<td><font Color ="<%#PickColor(DataBinder.Eval(Container.DataItem , "UnitsInStock"))%>">
<%#DataBinder.Eval(Container.DataItem , "UnitsInStock")%>
</font>
</tr>
</ItemTemplate>
<FooterTemplate >
</table>
</FooterTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>


Step 2 - In the code behind write the code which picks the color based on the value of the UnitsInStock.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Dim myconnection As SqlConnection = New SqlConnection("server=localhost;uid=sa;password=; database=northwind")
Dim myda As SqlDataAdapter = New SqlDataAdapter("Select * from Products", myconnection)
Dim ds As DataSet = New DataSet()
myda.Fill(ds, "AllTables")
DataGrid1.DataSource = ds
DataGrid1.DataBind()
End Sub

'Function to pick up the color based on th UnitsInStock Value
Function PickColor(ByVal fldval As Double) As String
Dim color As String
If fldval < 15 Then
color = "Red"
Return color
Else
color = "green"
Return "green"
End If
End Function

 

Source - http://www.c-sharpcorner.com/Code/2003/May/ChangeDataGridColumnColor.asp

Intersection of two arrays when comparison is based on only 1 key

A function to find intersection of two arrays when comparison is based on only 1 key

function array_common($array1,$array2,$compareString) {
if (!is_array($array1) || !is_array($array2)) {
return false;
}
$arrResult = array();
foreach ($array1 as $arrInsideArray1) {
foreach ($array2 as $arrInsideArray2) {
$found=false;
if ($arrInsideArray1[$compareString]==$arrInsideArray2[$compareString]) {
$found=true;
break;
}
}
if ($found) {
array_push($arrResult,$arrInsideArray1);
}

}
return $arrResult;
}