Query to get the length of string in mysql

In this programming tutorial you will learn how to get the length of string in mysql. I have already written the same tutorial for ms sql server. It is quite easy in mysql too. Let’s have a look over it.
Query to get the length of string in mysql
select length("Arman Malik") as length
Output:-
11

You can also use single quote within length() function like given below
select length('Arman Malik') as length

Output:-
11

Using single quote within the length() function can cause the sql injection if user will enter the ' and \ with the string like given below

select length('Arman's Malik')

It will throw the following error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Fakhar') as length' at line 1.

So if you want to prevent the sql injection then use double quotes within the length function but if you want to use the single quote within the length() function and also want to prevent the sql injection then use \ like given below

select length('Arman\'s Malik') as length

Output:-
13

So that's it. I hope you will found this tutorial very handy and informative.

I love your feedback.
Read more...

How to fix png transparency problem in IE 5.5 and 6

In this programming tutorial we will learn how to fix png transparency problem in IE 5.5 and 6. In Internet Explorer 6 and below, transparent png images do not show accurately. The transparent part of the png do not look transparent but it gives a solid color look. Now Microsoft has introduced IE 9 but we should always keep this thing in our mind that the user of our website can also visit our website from IE 6 or prior than IE 6. So we have to fix this issue. Let's have a look over how to fix this issue.

How to fix png transparency problem in IE 5.5 and 6

You just have to insert the following code in the head tag of your web page.
<!--[if lt IE 7]>
<script language="JavaScript" type="text/javascript">
function fixPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
window.attachEvent("onload", fixPNG);
</script>
<![endif]-->
So that's it. This is the way to fix the png transparency problem in IE 5.5 and 6.

This code will only execute if user's browser will be IE 6 or prior than IE 6. So there will be no extra load in your web browser if it is firefox, google chrome, opera, safari or internet explorer greater than 6.

I hope you will find this tutorial very informative.

I love your feedback.
Read more...

Learn how to get the date of last sunday in a month using asp.net with c#

In this programming tutorial you will learn how to get the date of last sunday in a month using asp.net with c#. It is quite easy in asp.net. Let`s have a look over how to do so.

Getting the date of last sunday in a month using asp.net with c#

   protected void Page_Load(object sender, EventArgs e)
    {
 DateTime currentDateTime=System.DateTime.Now;
        Response.Write(GetLastWeekdayInMonth(System.DateTime.Now, DayOfWeek.Sunday));

    }
    private static DateTime GetLastWeekdayInMonth(DateTime date, DayOfWeek day)
    {
        DateTime lastDayOfMonth = new DateTime(date.Year, date.Month, 1)
            .AddMonths(1).AddDays(-1);
        int wantedDay = (int)day;
        int lastDay = (int)lastDayOfMonth.DayOfWeek;
        return lastDayOfMonth.AddDays(
            lastDay >= wantedDay ? wantedDay - lastDay : wantedDay - lastDay - 7);
    }

Output
5/29/2011 12:00:00 AM

So this the way to get the date of last sunday in a month/get the date of last week day using asp.net with c#.

I hope you will find this tutorial very informative.

I love your feedback.
Read more...

How to get date for every sunday in a month using asp.net with c#

In this programming tutorial you will learn how to get the date for every sunday in a month using asp.net with c#. There are multiple methods to achieve our goal. Let`s have a look over them.

How to get date for every sunday in a month in asp.net using c#

Method 1
using System.Globalization;//Donot forget to declare this namespace
 protected void Page_Load(object sender, EventArgs e)
    {
 DateTime currentDateTime=System.DateTime.Now;
        int year=currentDateTime.Year;
        int months=currentDateTime.Month;
        GetDatesOfSundays(year, months, DayOfWeek.Sunday);
    }

    protected void GetDatesOfSundays(int year, int month, DayOfWeek dayName)
    {
        CultureInfo ci = new CultureInfo("en-US");
        for (int i = 1; i <= ci.Calendar.GetDaysInMonth(year, month); i++)
        {
            if (new DateTime(year, month, i).DayOfWeek == dayName)
                Response.Write(i.ToString() + ",");
        }
    }

Output
1,8,15,22,29

Method 2
protected void Page_Load(object sender, EventArgs e)
    {
     Response.Write(GetDatesOfSundays(System.DateTime.Now));

    }
private string GetDatesOfSundays(DateTime DatMonth)
    {
        string sReturn = "";
        int iDayOffset = DatMonth.Day - 1;
        DatMonth = DatMonth.AddDays(System.Convert.ToDouble(-DatMonth.Day + 1));
        DateTime DatMonth2 = DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
        while (DatMonth < DatMonth2)
        {
            if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
            {
                if (sReturn.Length > 0) sReturn += ",";
                sReturn += DatMonth.ToShortDateString();
            }
            DatMonth = DatMonth.AddDays(1.0);
        }
        return sReturn;
    } 
Output
5/1/2011,5/8/2011,5/15/2011,5/22/2011,5/29/2011

So these are the methods to find the sundays in a month using asp.net with c#.

I hope you will find this tutorial very informative.

I love your feedback.
Read more...

How to get the all user created tables saved in ms sql server database

In this programming tutorial you will learn how to get the all user created tables saved in ms sql server database. It is quite easy and simple. Only you have to do is to write and execute the following query.

How to get all user created tables saved in ms sql server database

SELECT * FROM SYS.OBJECTS WHERE TYPE ='u'
The above mentioned query will return you the all user created tables saved in ms sql server database. User created tables means the tables created by users, not the built-in system tables. Sys.Objects is a built-in table in ms sql server that has information about each and every element of the database.

I love your feedback.
Read more...

Query to get the length of string in ms sql server

In this programming tutorial you will learn the query that will get the length of string in ms sql server. It is quite easy in ms sql server. Let's have a look over it.

Query to get the length of string in ms sql server

select len('Arman Malik') as length;

Output
11

The above query will give you 12 as output because there are total 11 characters including space found in string.

That's it. Using built-in len() function of ms sql server you can do this very easily. In case if there is any apostrophe in string then you have to use another apostrophe before it like illustrated in example given below
select len('Arman Malik''s passion is programming') as length;
Output:-
37

I hope you will found this tutorial very handy and informative.

I love your feedback.
Read more...

Redirection after some time delay in php


In this programming tutorial we will learn how to perform redirection after some time delay in php. I have already written tutorials for same topic in javascript and asp.net. It is quite easy in php. I will demonstrate this with two methods. So let's have a look over how to do so.

Redirection after some time delay in php


Use Header Function
header("refresh:5;url=somepage.php");
Note:- If your php page also contains html code then use header function on very top of the page just before the <head> tag else you will get the headers already sent by... error.

Use Meta tag in echo or print statement
print "<meta http-equiv='refresh' content='5;url=somepage.php'>";

So that's it. I hope you will find this tutorial very handy.

I love your feedback

Read more...

Insertion of records in database using 3-tier architecture in asp.net with c#

In this tutorial we will discuss about how to insert records in database using 3-tier architecture in asp.net with c#. For beginners I strongly recommend to read this tutorial 3-Tier Architecture in asp.net using c# first to get basics of 3-tier architecture in asp.net. So let’s start.
3-Tier Architecture in asp.net

Insertion of records in database using 3-tier architecture in asp.net with c#

insert-records.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="insert-records.aspx.cs" Inherits="insert-records" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Insertion of records in database using 3-tier architecture in asp.net with c#</title>
</head>
<body>
<form id="form1" runat="server">
  <table width="600px" cellspacing="2" cellpadding="2" border="1" style="font-family:verdana;font-size:12px;">
    <tbody>
      <tr>
        <td colspan="2" align="left"><strong> User Feedback Form</strong></td>
      </tr>
      <tr>
        <td align="left" width="20%"> First Name </td>
        <td><asp:TextBox ID="txtFirstName" runat="server" Font-Size="Small" Width="250px"></asp:TextBox>
        </td>
      </tr>
      <tr>
        <td align="left"> Last Name </td>
        <td align="left"><asp:TextBox ID="txtLastName" runat="server" Font-Size="Small" Width="250px"></asp:TextBox>
        </td>
      </tr>
      <tr>
        <td> Feedback </td>
        <td><asp:TextBox ID="txtFeedback" runat="server" TextMode="MultiLine" Rows="12" Columns="50"></asp:TextBox>
        </td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td align="left"><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"/>
        </td>
      </tr>
    </tbody>
  </table>
</form>
</body>
</html>
As you have seen in code and image that we have two textboxes, one textarea and one button in our .aspx page. User will fill the form and click the button to submit his/her feedback. At button’s click event in code behind I have written all the logic to insert records in database using 3-tier architecture in asp.net with c#. Remember I have not performed any client side or server side validation on my form fields because I want to make code simple and clear for you and just want to focus on topic, so let’s have a look over its code behind file

insert-records.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BusinessLayer;//Donot forget to import this namespace


public partial class insert-records : System.Web.UI.Page
{
BusFeedback _objFeedback = new BusFeedback ();
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnSubmit_Click(object sender, EventArgs e)
    {
_objFeedback.InsertFeedback(txtFirstName.Text, txtLastName.Text, txtFeedback.Text);
 //If records successfully entered then redirect to feedback page
//Response.Redirect("view-feedback.aspx");
    }

}



I have declared the object of my bus BusFeedback that I am going to create after this explanation. The object that I declared is _objFeedback then on click event of asp:button I made call to the function written in BusFeedback, that will insert records in database and that’s it. I could write insertion function in BusComments that I created in my previous tutorial but for better understanding I am creating separate bus for insertion of records. I will recommend you to create one bus for one module and write all functions in it. Every module should have its own bus, it is better approach. Now let’s have a look over the bus.

For beginners I again ask you to read the basics of 3-tier architecture first by reading the tutorial 3-Tier Architecture in asp.net using c# in which I went in very detail about the benefits of 3-tier architecture, how to create business layer, how to create data access layer, how to create bus and write function in it and then how to call the function written in bus from .aspx page.

BusFeedback.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DataAccessLayer;//Donot forget to import this

namespace BusinessLayer
{
public class BusFeedback
{
DbAccess _dbAccess = new DbAccess();
private DataSet _FeedbackDS = new DataSet();
public DataSet FeedbackDS
{
get
{
return _FeedbackDS;
}
set
{
_FeedbackDS = value;
}
}

  //Function to insert data in database, in this example I used MS SQL SERVER    
  public void InsertFeedback(string firstName, string lastName, string feedback)
        {

            try
            {
                string str = "select max(id) as max_id from web_tbl_feedback";
                int maxVal = (_dbAccess.returnint32(str));
                string id = Convert.ToString(maxVal);
                if (string.IsNullOrEmpty(id))
                {
                    maxVal = 1;
                }
                else
                {
                    maxVal++;
                }

                string strInsert = "insert into web_tbl_feedback(id,firstname,lastname,feedback) values('" + maxVal + "','" + firstName + "','" + lastName + "','" + feedback + "')";
                _dbAccess.executeQuery(strInsert);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

}

}

As far as DataAccessLayer namespace and its bus DbAccess.cs is concered, if you are developing new project then you will have to create business layer with its bus busFeedback, DataAccessLayer with its bus DbAccess but if you are using the same project that we developed during previous tutorial then only you have to put BusFeedback in your BusinessLayer folder and that’s it, there is no need to create any DbAccess bus again because one project has only one DbAccess bus but on other end one project may have lot of buses in BusinessLayer folder because those buses depend over modules and DbAccess bus of DataAccessLayer depends over complete project.

So that’s it. Keep in touch as very soon I will write tutorial about deletion and updation of records using 3-tier architecture in asp.net with c#.

Happy Coding!!!

Read more...

How to get missing leading zero while conversion of number to string in javascript

In this tutorial I will discuss about how to get missing leading zero while conversion of number to string in javascript. I have faced this problem today and at that time i thought to share with you people so that you can save your half hour that i have wasted today for solving this problem :)

How to get missing leading zero while converting number to string in javascript

Today while developing the countdown module, i got a requirement to show the days value which was a number like 01,02,03,04.... up to 30, in two different spans in such a way that the leading 0 of 01 value should be shown in first span and then 1 in second span, likewise if we have 21 as a value then 2 will be shown in first span and 1 will be shown in second span. I Just want to clear your confusion, in my example the value of days variable change dynamically when countdown start. I was very much amazed when i saw the conversion of number 01 to string resulting in only 1, the conversion of number 02 to string resulting in only 2, and then suddenly i thought where is leading zero???
<script language="javascript" type="text/javascript">
var days=01;
var daysString=Number(days);
daysString=daysString.toString();
n1=daysString.substring(0,1);
n2=daysString.substring(1,2);
alert(n1);//it should give you 0 but it will give you 1
alert(n2);//It should give you 1 but it will give you nothing
</script>

So to solve this problem and get missing leading zero, you have to follow the example given below
<script language="javascript" type="text/javascript">
var days=01;
var daysString=Number(days);
daysString=daysString.toString();
if(daysString.length>1)
{
n1=daysString.substring(0,1);
n2=daysString.substring(1,2);
}
else if(daysString.length==1)
{
n1="0";
n2=daysString.substring(0,1);
}
else
{
n1="0";
n2="0";
}
alert(n1);//Now it will give you 0
alert(n2);//Now it will give you 1
</script>

The variable days store integer(Number, Numeric) value that comes dynamically, that's why the value is not surrounded by any " ". If days="01" then there was no problem by getting 01 as a 0 and 1 because any thing inside the double quotes is called string and we can get substring easily from string.

I know this tutorial is a bit technical but you will find this very much handy.

Thanks and Keep in touch.

Read more...

How to get the IP address in php

In this tutorial you will learn how to get the IP address in php. Sometimes $_SERVER['REMOTE_ADDR'] cannot give you the exact IP address. If your visitor is connected to the Internet through Proxy Server then $_SERVER['REMOTE_ADDR'] just returns the IP address of the proxy server not of the visitor's machine. Let's have a look over how to get the almost real one.

How to get IP address in php

function getIpAddress()
{
    if (trim($_SERVER['HTTP_CLIENT_IP'])!="")   //checking ip address from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    else if (trim($_SERVER['HTTP_X_FORWARDED_FOR'])!="")   //checking whether ip address is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$ip_address = getIpAddress(); // Get the visitor's IP Address
echo $ip_address;

The above code snippet first tries to get the direct IP address of visitor’s machine, if not available then try for forwarded for IP address using HTTP_X_FORWARDED_FOR. And if this is not available too then it will finally get the IP address using REMOTE_ADDR. So that's it.


Happy Coding!!!
Read more...

Difference between varchar and nvarchar

The wide range of data types in MS SQL Server can sometimes throw people through a loop, especially when the data types look highly interchangeable. VARCHAR and NVARCHAR seem to be highly interchangeable but there is some sort of difference between them. Let’s discuss it.

Difference between varchar and nvarchar

VARCHAR is an abbreviation for variable-length character string. It is a string of text characters that can be as large as the page size for the database table holding the column in question. Normally the size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters. So the maximum size of a VARCHAR is 8,000 bytes. Varchar stores ascii data.

The additional "N" in NVARCHAR means uNicode. Essentially, NVARCHAR is identical to VARCHAR but it supports two-byte characters. The most common use for this type of thing is to store character data that is a mixture of English and non-English symbols such as English and Chinese. Simply nvarchar stores unicode data and takes twice space than varchar

So that's it. I love your feedback.
Read more...

Send email with CC and BCC in php

In this tutorial you will learn how to send email with CC and BCC in php. I have already written a tutorial about sending html emails using php in which I have written a custom made function send_email($from, $to, $subject, $message) to send html email. You just have to add the two lines of code in that function and that's it. Let's have a look over how to do so

Send email with CC and BCC in php

function send_email($from, $to, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Reply-To: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n"; 
$headers .= "CC: sombodyelse@gmail.com\r\n";
$headers .= "BCC: hiddenemail@gmail.com\r\n";
//set content type to HTML 
$headers .= "Content-type: text/html\r\n"; 

if ( mail($to,$subject,$message,$headers) ) 
{
header("location:yourdesirepage.php?msg=sent");

} 
else 
{
header("location:yourdesirepage.php?msg=notsent");
}
}
//Function ends here
$from_email="fromyou@gmail.com";
$to_email="tosomeone@gmail.com";
$subject="Subject of Email";
$message.="<html><body>";
$message.="<strong>Your message here will be look bold when visible to reader</strong>";
$message.="Some more message";
$message.="</body></html>";
send_email($from_email,$to_email,$subject,$message);



In the send_email() function, i used two more headers CC and BCC to send email with CC and BCC in php.

$headers .= "CC: sombodyelse@gmail.com\r\n";
CC means Carbon Copy. A comma separated list of more recipients that will be seen by all other recipients.
$headers .= "BCC: hiddenemail@gmail.com\r\n";

BCC means Blind Carbon Copy. A comma separated list of more recipients that will not be seen by any other recipients.

Note:-Be remember, Header names are case sensitive. Each header is ended with the Return and Newline characters \r\n. There are no spaces among header name.


So that's it.




Happy coding!!!
Read more...

Import excel data to gridview

In this tutorial you will learn how to import excel data to gridview control. I have already written multiple posts for exporting gridview data to excel with different techniques, now its time to import records. Let's have a look over how to do so

Import excel data to gridview

.aspx page

<table width="100%" cellpadding="0" cellspacing="0">
                    <tr>
                        <td align="left" class="text" style="width: 114px;">
                           Import Data from Excel File
                        </td>
                        <td align="left">
                            <asp:FileUpload ID="uploadExcel" runat="server" />
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            <asp:Button ID="btnImport" runat="server" Text="Import Data" OnClick="btnImport_Click" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:GridView ID="GridView1" runat="server">
                                <Columns>
                                    <asp:TemplateField HeaderText="First Name">
                                        <ItemTemplate>
                                            <asp:Label ID="lblFirstName" runat="server" Text='<%# Bind("first_name") %>'></asp:Label>
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Left" />
                                    </asp:TemplateField>
                                    <asp:TemplateField  HeaderText="Last Name
                                        <ItemTemplate>
                                            <asp:Label ID="lblLastName" runat="server" Text='<%# Bind("last_name") %>'></asp:Label>
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Left" />
                                    </asp:TemplateField>
                                    <asp:TemplateField  HeaderText="Gender">
                                        <ItemTemplate>
                                            <asp:Label ID="lblGender" runat="server" Text='<%# Bind("gender") %>'></asp:Label>
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </td>
                    </tr>
                </table>



Simply we have a fileupload control, button control and gridview control in our page. We will use file upload control to upload the excel file and then using its physical path we will get records from it and display them to gridview control.


.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;

protected void btnImport_Click(object sender, EventArgs e)
    {
        try
        {
            string path = uploadExcel.FileName;
            uploadExcel.SaveAs(Server.MapPath("~/Upload/" + path));
            OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0");                
            oconn.Open();    
//Getting records from Sheet1 of excel file. As you know one excel file may have many sheets                    
            OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);
            DataSet ds = new DataSet();
            OleDbDataAdapter odapt = new OleDbDataAdapter(ocmd);
            odapt.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            oconn.Close();            
        }
        catch(Exception exp)
        {
            throw exp;
        }            
    }

Note:- Don't forget to import namespaces that i have used above.


So this is the way to import excel data to gridview


Happy Coding!!!
Read more...