I have a php file that reads a csv file and pulls the data and displays it on the site. But unfortunately I don't know why it creates an extra line which sets the counter to go wrong... How do i fix that?

This is my code:

<style> table{width:100%; border-collapse:collapse; border:3px solid red; font-size: 10px;} td {font-size: 10px; border: 1px solid blue;border-collapse:collapse; text-align: left; width: 50px; padding-top: 1px; padding-left: 1px;} th {background: #ffb300; text-align: left; padding-top: 1px; padding-left: 1px; font-size: 10px;} tr:hover {color: red; font-size: 10px;} .dark {background: #ffb300;} .light {background: #ffb300;} first_name {width: 50px;} last_name {width: 50px;} email {width: 50px;} telephone {width: 50px;} reason {width: 50px;} time {width: 20px;} comment {width: 150px;} count {width: 20px;}    today {width: 30px;}</style>




<?php


echo "<html><body><table style=''>";//Table style is empty 
$f = fopen("csv.csv", "r"); //File csv.csv is openned and read only "r"
$trcount = 0; //This is just to set a counter for making sure that we have alternating rows 

while (($line = fgetcsv($f)) !== false) { //$line = the content of $f which is the content of the CSV --- First Row
        $trclass = ''; //It has a table row class formating that is set to nothing... 
        if ($trcount%2==0) 
                          { $trclass=' class="dark"'; } //if count divided by 2 has no remainder then it is even otherwise no formating and it is light.    
            echo "<tr".$trclass.">\n"; //Just echos background for the row ONLY!!!!

    $tdcount = 1; //reset to 0 for each inner loop
        foreach ($line as $cell) {
                $tdclass = ''; 
                if ($tdcount%2==0) 

                       { $tdclass='class="light"'; } //default to nothing, but if it's even apply a class


                echo "<td ".$tdclass."style='padding:.4em;'>" . htmlspecialchars($cell) . "</td>"; //same as before, but now this also has the variable $class to setup a class if needed
                $tdcount++; //go up one each loop
        }
      //  echo "\r</tr>";
        $trcount++; //go up one each loop 
}
fclose($f);
echo "</table></body></html>";
?>

Recommended Answers

All 16 Replies

Member Avatar for LastMitch

@<MICHAEL>

But unfortunately I don't know why it creates an extra line which sets the counter to go wrong... How do i fix that?

Do you have a picture of your table?

I can't believe that you didn't finish this project yet.

All you been doing is spamming all over daniweb.

... i have not been spamming...

Don't think that this is the only project i work on... but yes i do work on this one a lot... so please lose the thought of me only working on 1 project. I am not a pro, you are. I am not even an amateur, I am a beginner.

But anyways... here is an example of what I get... (view attachment)

Please tell me if you need to see what it looks like with more inqueries!

Line 30 probably should not be commented out, unless I've overlooked a closing </tr> tag somewhere else.

It may also be helpful if you could post a sample of your CSV file too, just to check that all lines contain the same number of comma separated values and no blank lines.

Here is a snapshot of the csv viewed in excel... it skips a line in the csv, so it would skip a line as seen on the site.

I will try out your idea on commenting out line 30, probably not this very instance because its 1 am, and I have to be up at 4...

Here is a snapshot of the csv viewed in excel... it skips a line in the csv, so it would skip a line as seen on the site.

So you want a blank line? Because your original post alludes to that being the problem.

What exactly are you trying to do, and what exactly is the problem?

no, i don't want a blank line because it causes the counter to go wrong.

The problem is that an extra line is created that is completely blank (look on the attachment that I attached above, not the excel preview). The blank line causes it to count 1,2,4,8... and so on.
But if the extra line is removed, it would count 1,2,3,4,5... which is what i want.

Member Avatar for diafol

Here's an old general function I spruced, which may be of use - perhaps not. :)

<style>
    .striped tr th, .striped tr td.selected {
        background-color: #99ff99;
    }
    .striped th, .striped td{
        border: 1px black solid;
        padding: .4em;  
    }
    .striped{
        border-collapse:collapse;
    }
</style>

<?php 
function CSV2Table($filename, $filter=true, $striping = true){

    if(!file_exists($filename))return 'No file was found';
    $header = '';
    $data = '';
    $content = str_getcsv(file_get_contents($filename), "\n"); 
    foreach($content as $line) $rows[] = ($filter) ? array_filter(str_getcsv($line, ",")) : str_getcsv($line, ",");
    $rows = ($filter) ? array_filter($rows) : $rows;
    foreach($rows as $row){
        if($header == ''){
            $header = '<thead><tr>';
            foreach($row as $cell){
                $header .= "<th>$cell</th>";
            }
            $header .= '</tr></thead><tbody>'; 
        }else{ 
            $startcell = 0;
            $data .= "<tr>";
            //The $striping could be further developed for different next child cases in CSS
            foreach($row as $cell){
                $class = ($startcell % 2 && $striping) ? ' class="selected"' : ''; 
                $data .= "<td$class>$cell</td>";
                $startcell++;
            }
            $data .= "</tr>";
        }
    }            
    $table = '<table class="striped">' . $header . $data . '</tbody></table>';
    return $table;
}

echo CSV2Table('../small.csv');

This ain't production code!! I created it to display tables where the data was unknown - no clue about number of columns - other than a header line was included as Line #1). It skips blank rows by filtering out blank arrays. Must be a better way to do that though.
I just added some stuff for column striping.

EDIT
//I can see a problem with incomplete rows though

@diafol hit the nail on the head.

I was going to suggest that if you were unable to remove the blank lines from your CSV, that you instead test for their presence when iterating through the data.

If the blank lines are truly empty, i.e. there are no spaces or anything, then adding something like the following should solve the issue. See lines 11 and 12.

<?php

$handle = fopen('csv.csv', 'r');
$row_count = 0;
echo '<html><body><table>';

// Iterate through each line of CSV file
while(($line = fgetcsv($handle)) !== false)
{
    // Skip line if empty
    if(! $line)
        continue;

    $row_class = $row_count % 2 ? '' : 'dark';
    $cell_count = 0;

    echo "<tr class=\"{$row_class}\">";

    // Iterate through each line value
    foreach($line as $value)
    {
        $cell_class = $cell_count % 2 ? '' : 'light';

        echo "<td class=\"{$cell_class}\">" . htmlspecialchars($value) . '</td>';
        $cell_count += 1;
    }

    echo '</tr>';
    $row_count += 1;
}

echo '</table></body></html>';
fclose($handle);
commented: that's easier :) +14

Thanks blocblue, your resource was helpful, but the counter is still off. That's okay at the moment, I will investigate that and come right back!

Well, i tried adding some increment/decrement symbols on #row_count ++=1; that didn't work... do you guys know what causes the counter to go wrong? could the counter be wrong wrong due to a php file using the same csv file and overwriting the other php file?

So... from my other file that populates the csv from the web data I managed to pull this

$count= count(file("main_form.csv"));                       
                        $today = date("d M Y h:i A");
                        echo $today;



$cvsData = "\n" . $count . "," . $today . "," . $first_name . "," . $last_name . "," . $email . "," . $telephone . "," . $reason . "," . $time . "," . $comment . "\n";

$fp = fopen("main_form.csv", "a" );
if($fp){
    fwrite($fp, $cvsData);
    fclose($fp);
    }                   

Could this have something to do with creating an extra line that causes the counter to go wrong?

Sorry guys if I am becomming annoying, I am trying to master this!

I should have marked this solved 1 month ago, but I figured it out by searching through the php.net site and found a simple solution that fixed the issues. Thanks you guys!

Member Avatar for diafol

Perhaps you could share the solution here for users seeking similar help?

Sure thing, i followed this page to fix the counter:
http://php.net/manual/en/function.count.php

Plus i didn't notice that i had some syntax flaws that created the extra lines... So i fixed it that way. But thanks for helping :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.