lundi 13 août 2018

Want to save all values of checkbox in csv (php), unfortunately only one gets saved

I have a form and I am exporting the answers into a csv file. Radio buttons working fine. The value of the textarea is not getting exported and the value of all selected checkboxes is also not exported. Only one value gets exported. What I am doing wrong? Please help!

My code index.php

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 0);
    include 'php/create-csv.php';
    ?>


    <!DOCTYPE html>
    <html lang="de">
    <body>
    <form method="post" action="" name="contactform">
    <div class="control-group">
     <label class="control control-checkbox"> Insurances            
      <input type="checkbox" value="insurances" name="topic[]"/>
      <div class="control_indicator"></div>
     </label>
     <label class="control control-checkbox"> Savings
      <input type="checkbox"  value="savings" name="topic[]"/>
      <div class="control_indicator"></div>
     </label>
     <label class="control control-checkbox"> Other
      <input type="checkbox" value="other_topic" name="topic[]"/>
      <div class="control_indicator"></div>            
     </label>
     <div id="textarea">
      <textarea rows="4" cols="40"  name="other"></textarea>
      </div>
     </div>
    <input type="submit" name="submit" value="Send" id="submit" 
    class="submit-btn">
     <?php
       if (isset($errors)) {
        foreach ($errors as $error) {
          echo $error;
        }
       }      
      ?>
   </form>

</body>

</html>

Code for create-csv.php

<?php
  if (isset($_POST['submit'])) {
   $topic = isset($_POST['topic']) ? $_POST['topic'] : '';
   $rating = isset($_POST['rating']) ? $_POST['rating'] : '';
   $other = isset($_POST['other']) ? $_POST['other'] : '';

    if ($rating == '') {
        $errors[] = '<div class="notification error clearfix"><p>Please select a number.</p></div>';
    }
    if ($topic == '') {
     $errors[] = '<div class="notification error clearfix"><p>Please select at 
          least one topic.</p></div>';
    }  
    if (!isset($errors)) {

        if(!empty($_POST['topic'])) {    
            foreach($_POST['topic'] as $value){  
                echo $value; 
            }
        }

        $header = "Rating,Topics,Other\n";

        $data = "$rating, $topic, $other\n";
    $fileName = dirname(__DIR__) . "/results.csv";



            if (file_exists($fileName)) {

                file_put_contents($fileName, $data, FILE_APPEND);
            } else {

                file_put_contents($fileName, $header . $data);
            } 
             header("Location: thankyou.html");
            exit;


        }
    }




Aucun commentaire:

Enregistrer un commentaire