[SOLVED] Query CSV File

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
daveluff
Forum Newbie
Posts: 7
Joined: Fri Jul 23, 2004 6:32 am

[SOLVED] Query CSV File

Post by daveluff »

Hi people,
I have a csv that consists of four fields.

email,FirstName,SecondName,nameID

Is it possible to have a php script that will query the csv and return data based on the nameID attribute. I will pass in the nameID from flash.

Thanks a lot for your time,
Dave
litebearer
Forum Contributor
Posts: 194
Joined: Sat Mar 27, 2004 5:54 am

Post by litebearer »

This should do the trick...

Code: Select all

<?PHP

// set your search nameid

$what_id = "JM102";

// set a found flag

$found = FALSE;


// put the entire csv file into an array

$all_lines = file('people.csv'); 

// count the number of lines in the file and store it in a variable

$how_many_lines = count($all_lines);

// take each line and 
//	1. separate each line into its individual elements (aka fields aka pieces of information)
//	2. grab the value(s) you are going to test and place them in a variable.


for ($i = 0; $i < $how_many_lines; $i++) { 
  $all_fields[$i] = explode(',', $all_lines[$i]); 
  $email = trim($all_fields[$i][0];
  $first_name = trim($all_fields[$i] [1]);
  $last_name = trim($all_fields[$i] [2]);
  $name_id = trim($all_fields[$i] [3]);
  if ($name_id == $what_id) {
	  $i = $how_many_lines + 5;
    $found = TRUE;
  }
}

// check to see if a match was found

if (!$found) {
 echo "No match found in the file";
 exit;
}

// if it gets this far then a match was found
// so do the rest of your coding

?>
daveluff
Forum Newbie
Posts: 7
Joined: Fri Jul 23, 2004 6:32 am

Post by daveluff »

cheers thanks a lot I'll give it a go.
Your help is really appreciated.

Dave
daveluff
Forum Newbie
Posts: 7
Joined: Fri Jul 23, 2004 6:32 am

Post by daveluff »

worked perfectly :lol:
Post Reply