Wednesday, January 30, 2013

Read and Write CSV File In PHP


Read and Write CSV File  


comma-separated values (CSV) file stores tabular data (numbers and text) in plain-text form. Plain text means that the file is a sequence of characters, with no data that has to be interpreted instead, as binary numbers. A CSV file consists of any number of records, separated by line breaks of some kind; each record consists of fields, separated by some other character or string, most commonly a literal comma or tab. Usually, all records have an identical sequence of fields.

So First we will see the structure of an CSV file.

one, two

example1, example2
data1, data2
test1, test2

now first we see how to read from a CSV file, here we go we will use php function "fgetcsv" it will read the content of csv file as given in example

<?php

function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}

// Set path to CSV file

$csvFile = 'test_data.csv';

//calling the function

$csv = readCSV($csvFile);
if(!empty($csv)){
    foreach($csv as $file){
        //inserting into database
        $query_insert = "insert into csv_data_upload set 
            name    =   '".$file[0]."',
            value   =   '".$file[1]."'";
            echo $query_insert;
        $insert = mysql_query($query_insert);   
  }
}else{
   echo 'Csv is empty'; 
    
}

?>



On executing this code the data will get stored in database.

Now how to write into an CSV File
for that we are going to use "fputcsv"
fputcsv  formats a line as csv and write it to the specified file handle.

for example


<?php

$list = array (

    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');


foreach ($list as $fields) {

    fputcsv($fp, $fields);
}

fclose($fp);


?>


Following code will write into CSV File.

        


Friday, January 25, 2013

Sample C Programs


Basic C Programs for Technical Interviews

1. Program to show swap of two no’s without using third variable.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("enter value for a & b: ");
scanf("%d%d",&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf("after swapping the value of a & b: %d %d",a,b);
getch();
}


2. Program to reverse a given number:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,a,r=0;
clrscr();
printf("enter any no to get its reverse: ");
scanf("%d",&n);
while(n>=1)
{
a=n%10;
r=r*10+a;
n=n/10;
}
printf("reverse=%d",r);
getch();
}


3. Program to find greatest in 3 numbers.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter value of a, b & c: ");
scanf("%d%d%d",&a,&b,&c);
if((a>b)&&(a>c))
printf("a is greatest");
if((b>c)&&(b>a))
printf("b is greatest");
if((c>a)&&(c>b))
printf("c is greatest");
getch();
}


4. Program to find whether given no is even or odd.

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("enter any no: ");
scanf("%d",&n);
if(n%2==0)
printf("no is even");
else
printf("no is odd");
getch();
}


5. Program to display first 10 natural no & their sum.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,sum=0;
clrscr();
for(i=1;i<=10;i++)
{
printf("%d no is= %d\n",i,I);
sum=sum+i;
}
printf("sum =%d",sum);
getch();
}


6. Program to find factorial of a number.

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,fact=1;
clrscr();
printf("Enter any no: ");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
fact=fact*i;
}
printf("Factorial=%d",fact);
getch();
}


7. Program to find whether given no is a prime no or not.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,r=0;
clrscr();
printf("Enter any no: ");
scanf("%d",&n);
for(i=2;i<=n-1;i++)
{
if(n%i==0)
r=1;
break;
}
if(r==0)
printf("prime no");
else
printf("Not prime");
getch();
}


8. Program to add two number using pointers.

#include<stdio.h>
#include<conio.h>
void main()
{
int *p1,*p2,sum;
clrscr();
printf("enter two no's: ");
scanf("%d%d",&*p1,&*p2);
sum=*p1+*p2;
printf("sum=%d",sum);
getch();
}


9. Program to find multiplication of two matrices.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2],b[3][2],c[3][2],i,j;
clrscr();
printf("enter value for 1 matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("enter value for 2 matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
c[i][j]=a[i][j]*b[i][j];
}
printf("matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(" %d ",c[i][j]);
}
printf("\n");
}
getch();
}


10. Program to reverse a number using pointer.

#include<stdio.h>
#include<conio.h>
void main()
{
int *n,a,r=0;
clrscr();
printf("enter any no to get its reverse: ");
scanf("%d",&*n);
while(*n>=1)
{
a=*n%10;
r=r*10+a;
*n=*n/10;
}
printf("reverse=%d",r);
getch();
}


11. Program to swap two numbers using functions.

#include<stdio.h>
#include<conio.h>
void main()
{
void swap(int,int);
int a,b,r;
clrscr();
printf("enter value for a&b: ");
scanf("%d%d",&a,&b);
swap(a,b);
getch();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("after swapping the value for a & b is : %d %d",a,b);
}


12. Program to find factorial of a number using functions.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,f;
int fact(int);
clrscr();
printf("enter a no: ");
scanf("%d",&a);
f=fact(a);
printf("factorial= %d",f);
getch();
}
int fact(int x)
{
int fac=1,i;
for(i=x;i>=1;i--)
fac=fac*i;
return(fac);
}


13. Program to show call by value..

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,swap();
clrscr();
a=5;
b=10;
printf("value of a=%d & value of b=%d before swap ",a,b);
swap(a,b);
printf("\nvalue of a =%d & b=%d after swap",a,b);
getch();
}
int swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}


14. Program to show call by reference.

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*aa,*bb,swap();
clrscr();
a=5;
b=10;
aa=&a;
bb=&b;
printf("value of a= %d & value of b=%d before swap",a,b);
swap(aa,bb);
printf("\nvalue of a=%d & b=%d after swap",a,b);
getch();
}
int swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}


15. Program to find factorial of a number using recursion.

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("enter number: ");
scanf("%d",&n);
if(n<0)
printf("invalid number");
else
printf("%d!=%d",n,fact(n));
getch();
}
int fact(int x)
{
if(x==0)
return 1;
else
return(x*fact(x-1));
}


16. Program to find whether a string is palindrome or not.

#include<stdio.h>
#include<conio.h>
void main()
{
char s1[20],s2[20];
clrscr();
printf("enter a string: ");
scanf("%s",s1);
strcpy(s2,s1);
strrev(s2);
if(strcmp(s1,s2)==0)
printf("string is a palindrome");
else
printf("not a palindrome string");
getch();
}



Thursday, January 24, 2013

PHP Header Problem Solution(Cannot modify header information )

php – Cannot modify header information – headers already sent by (php header already sent error)

This error comes when you print any thing before php header command

PHP handles lots of the work of generating web pages for you, without you even having to ask. A web page is composed of two parts, the header and the body.
When a coder makes a mistake in the manipulation or creation of the headers, this common php error is seen. Here is an example:
Warning: Cannot modify header information – headers already sent by (output started at /home/usr1/public_html/sent.php:42) in /home/usr1/public_html/includes/theme-header.php on line 12
The header is generally stuff that you don’t need to worry about, is generated automatically, and contains information about the page, the server, related cookies. The header information is important, but it is not typically seen by the user. Here is an example:
Example Error Code:
<?php
print “text”;
header(‘Location: http://www.example.com/&#8217;);
?>
Solution :
<?php
function FunJavaScriptRedirection($url)
{?>
<script type=”text/javascript”>
<!–
window.location = “<?=$url?>”
//–>
</script>
<?}
print “test”;
FunJavaScriptRedirection(“http://www.example.com/&#8221;);
?>
The header must come first in the response from a web server and is separated from the body by one blank line. The reason this error occurs is that some part of the body of the web page has been sent to the user already when a request is made to set a header value. Because PHP simplifies many things for you, the problem may be hiding in plain site. Here are some guidelines for finding the problem:
1) Find the header() statement that is causing the problem. The error must be at or before this line.
2) Look for any statements that could send output to the user before this header statement. If you find one or more, change your code to move the header statement before them. Complex conditional statements may complicate the issue, but they may also help solve the problem. Consider a conditional expression at the top of the PHP script that determines the header value as early as possible and sets it there.
3) Make sure there is no white space outside of the php start and end tags. While a blank line before the<?php start tag may look innocent, when processed by PHP, it will turn into an echo statement printing out a blank line. This is a common culprit.


Wednesday, January 23, 2013

Find Nth Highest Salary of Employee – SQL

This question is quite a popular question and it is interesting that I have been receiving this question every other day. I have already answer this question here. “How to find Nth Highest Salary of Employee”.

Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary:

Employee
Employee IDSalary
3250
4700
7400


Now, here is what the SQL will look like:

SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)

Running the SQL above would return us “400″, which is of course the 2nd highest salary in the Employee table. 

An explanation of the solution

The SQL above first finds the highest salary value in the Employee table using “(select MAX(Salary) from Employee)”. Then, adding the “WHERE Salary NOT IN” in front basically creates a new set of Salary values that does not include the highest Salary value. For instance, if the highest salary in the Employee table is 200,000 then that value will be excluded from the results using the “NOT IN” operator, and all values except for 200,000 will be retained in the results.
This now means that the highest value in this new set will actually be the 2nd highest value in the Employee table. So, we then select the max Salary from the new result set, and that gives us 2nd highest Salary in the Employee table. That’s pretty interesting right?

An alternative solution using the not equals SQL operator

select MAX(Salary) from Employee WHERE Salary &lt;&gt; (select MAX(Salary) from Employee )

How would you write a SQL query to find the Nth highest salary?

What we did above was find the 2nd highest Salary value in the Employee table. But, what if we want to find the Nth highest salary, where N can be any number whether it’s the 3rd highest, 4th highest, 5th highest, 10th highest, etc? This is also an interesting question – try to come up with an answer yourself before reading the one below to see what you come up with.

The answer and explanation to finding the nth highest salary

SELECT * FROM Employee Emp1 WHERE (N-1) = (SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2 WHERE Emp2.Salary &gt; Emp1.Salary)

How does the query above work?

The query above can be quite confusing if you have not seen anything like it before – the inner query is what’s called a correlated sub-query because the inner query (the subquery) uses a value from the outer query (in this case the Emp1 table) in it’s WHERE clause. 
The most important thing to understand in the query above is that the sub-query is evaluated each and every time a row is processed by the outer query. In other words, the inner query can not be processed independently of the outer query since the inner query uses the Emp1 value as well.