0

I'm trying to read data from a CSV file and display it in a table. However, instead of being displayed in multiple columns, all the data are being displayed in a single column.

At first I've created a form and recorded the input in the CSV file in the following way:

<?php
# save the form data in csv file
$myfile = fopen("data.csv", "a+");
foreach ($_POST as $key) {
    fputcsv($myfile, explode(",", $key));
}
fclose($myfile);
?>

Then I've created a table using html and read from the file in the following way:

    <div class="container">
        <table>
            <tr>
                <th>Username</th>
                <th>Email</th> 
                <th>Password</th>
            </tr>
            <?php
            # read from the csv file
            $f = fopen("data.csv", "r");
            while (($line = fgetcsv($f)) !== false) {
                echo "<tr>\n";
                foreach ($line as $cell) {
                    echo "<td>" . htmlspecialchars($cell) . "</td>";
                }
                echo "</tr>\n";
            }
            fclose($f);
            echo "\n</table>";
            ?>
        </table>
    </div>

Here's what I'm getting as output:
enter image description here

As you can see, all the input are in single column But I want the username, email and password in their respective column.

1
  • You do not show var_dump($_POST) and/or the HTML <form>. Commented Mar 31, 2019 at 4:46

1 Answer 1

1

Your problem is that you are writing all your form data values onto separate lines in your first piece of code, so you are only reading back one value at a time in the second piece of code. You need to change

foreach ($_POST as $key) {
    fputcsv($myfile, explode(",", $key));
}

to

fputcsv($myfile, $_POST);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.