I'm trying to avoid using MySQL by using my CSV file on the server. I need to pull out my students information from each class based on their age. I've been reading about the use of 'fgetscsv' but would not know how to apply it.

Here's how the csv file looks like
(TEACHER,AGE,SUBJECT,NAME)

MS James,10,math,john
MS James,10,math,jamie
MS James,9,english,judy
MS James,10,english,jordan
MS James,9,english,david
MR Henington,10,english,tina
MR Henington,9,math,mike
MR Henington,9,math,mathew

Example:
I'm trying to echo only rows that has students that are 10 years old to come out like this:

"
Hi I'm John and I'm 10 years old. My favorite subject is math
Hi I'm Tina and I'm 10 years old. My favorite subject is english
etc.
"

Here's what I have.

echo "<table>";

$handle = fopen("students.csv", "r");
$data = fgetcsv($handle, 1000, ",");

data rows:

$thisRow = 1;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{

if($thisRow++ % 2 == 0){$bg = "#DEF0C2";}
else{$bg = "#E9F5D6";}

$teacher=$data[0];
$age=$data[1];
$subject=$data[2];
$name=$data[3];

echo "<tr style='background-color: $bg'>";

echo "<td>Hi I\m $name and I\'m $age years old. My favorite subject is $subject.</td>";

echo "</tr>\n";
}
echo "</table>\n";

Any help would be great.

    You could do a check of the age value, and do a continue; if it's not one you want. Here's my stylistically modified version (I obviously have no life):

    <?php
    $fh = fopen('test.csv', 'r');
    if($fh)
    {
       $thisRow = 1;
       echo "<table>\n";
       while(($line = fgetcsv($fh)) !== FALSE)
       {
          if((int)$line[1] != 10)
          {
             continue; // skip this one, wrong age
          }
          $bg = ($thisRow++ % 2) ? "#E9F5D6" : "#DEF0C2" ;
          printf(
             "<tr style='background-color: %s'>\n" .
             "<td>Hi I'm %s and I'm %d years old.\n" .
             "My favorite subject is %s.</td>\n</tr>\n",
             $bg,
             ucwords($line[3]),
             (int)$line[1],
             $line[2]
          );
       }
       echo "</table>\n";
    }
    else
    {
       echo "<p style='color: red'>ERROR: unable to read CSV file.</p>\n";
    }
    ?>
    

      Thanks for the fast reply. I've tested it and it seems to give me very high cpu load on my localhost. It didn't generate anything (still loading) because I had to shut my browser. I have over 300-500 students and I'm assuming it's manually checking each row on by one?

        Hmmm...something else must be going on. I just tried my code against a 1000-line CSV file, and it took less than a second to display the entire page (running locally on my PC). Sounds like you got an infinite loop in there somewhere.

          Well this was an interesting error to diagnose.

          If you'll visit the manual page for [man]fgetcsv/man, you'll see that the function has been available since PHP4 and that the manual claims that every parameter after the file resource is optional. This is only true in PHP5!

          In PHP4, which I suspect you are using, you must specify a length parameter, otherwise you'll get a "Wrong parameter count for fgetcsv()" error. Yet another mistake in the manual comes into play here as well; instead of returning FALSE in PHP4 (due to the missing length parameter), the function returns NULL, effectively creating an infinite loop of error messages being outputted to your browser.

          Solution: Add a length parameter to the function to ensure it works on both PHP4 and PHP5. For more information about this parameter, see the manual page for [man]fgetcsv/man (assuming they even got that much right... :p).

          EDIT: NogDog... you have a knack for posting replies after I hit the "reply" button yet before I finish typing! :p

          EDIT2: D'oh... I need to learn how to read. Apparently, the manual DOES mention the length being optional in PHP 5 only... I just glanced at it, saw the bracket before ", int $length" in the description, and assumed it was optional for PHP4 as well.

            I added the code below and it has worked successfully. Thankyou very much for the help 🙂

            while(($line = fgetcsv($fh, 500, ",")) !== FALSE)

              EDIT: LOL - we're all stepping on each other's posts here. 🙂 Glad you got it working.

              I think Brad might have the answer, as I was testing on PHP5. Try putting the 2nd parameter (length) back in for the fgetcsv() call, and see if that fixes it.

                Sorry, I have another question. Is there a way I can alphabetically sort by names after pulling their age?

                  Easiest way to do that, IMHO, would be to store the data as an array:

                  $array[$name] = array('teacher' => $teacher, 'age' => $age, 'subject' => $subject);

                  Obviously, you'd need to change the variables to the appropriate $line[] reference, but creating an array like this would allow you to use a function like [man]ksort/man.

                  Alternatively, you'd look at using something like [man]array_multi_sort/man.

                  EDIT: I've unmarked this thread as resolved - don't forget to re-mark it resolved when you've found an answer to your question.

                    I've tried using array_multi_sort but I am still confused on how to apply it. Can you give me an example based on NogDogs?

                      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
                      <html lang='en'>
                      <head>
                      <meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>
                      <title>Untitled</title>
                      <meta name="description" content="">
                      <meta name="keywords" content="">
                      <!-- link rel='stylesheet' href='/include/style.css' type='text/css' -->
                      <style type="text/css">
                      <!--
                      -->
                      </style>
                      </head>
                      <body>
                      <?php
                      $fh = fopen('test.csv', 'r');
                      if($fh)
                      {
                         $thisRow = 1;
                         echo "<table>\n";
                         $data = array();
                         while(($line = fgetcsv($fh, 1024)) !== FALSE)
                         {
                            if((int)$line[1] != 10)
                            {
                               continue; // skip this one, wrong age
                            }
                            $data[] = $line;
                         }
                         usort($data, create_function('$a, $b', 'return(strcmp($a[3],$b[3]));'));
                         foreach($data as $line)
                         {
                            $bg = ($thisRow++ % 2) ? "#E9F5D6" : "#DEF0C2" ;
                            printf(
                               "<tr style='background-color: %s'>\n" .
                               "<td>Hi I'm %s and I'm %d years old.\n" .
                               "My favorite subject is %s.</td>\n</tr>\n",
                               $bg,
                               ucwords($line[3]),
                               (int)$line[1],
                               $line[2]
                            );
                         }
                         echo "</table>\n";
                      }
                      else
                      {
                         echo "<p style='color: red'>ERROR: unable to read CSV fiel.</p>\n";
                      }
                      ?>
                      </body>
                      </html>
                      

                        Thank you VERY much NogDog.

                          23 days later

                          I've been trying to mess with array_unique but how do I filter duplicates based on names?

                            For the sake of clarity, and keeping this thread based on its original purpose, you might want to post a new topic for this new issue.

                              Write a Reply...