保存表单数据并存储为csv文件

时间:2018-01-09 00:26:20

标签: php forms csv

我正在尝试将PHP文件编码到我的网站中。我有一个用HTML创建的表单,其中包含字段名字,姓氏和电话号码。当用户单击提交按钮时,我希望将这3个字段保存并存储在csv文件中,当然,如果它通过了所有验证。但是,由于某种原因,我的代码似乎没有存储输入的任何数据。

以下是HTML代码:

   <?php include 'php/form.php',;?>

    <div class="formme">
      <form action="php/form.php">
       <div class="form-1">
            <div class="col-1">
                <label for="fname" class="fname">First name</label>
            </div>
          <div class="ph-1">
                <input type="text" id="fname" name="firstname" placeholder="Your name..">
          </div>
        </div>

        <div class="form-2">
          <div class="col-2">
            <label for="lname" class="lname">Last name</label>
          </div>
          <div class="ph-2">
            <input type="text" id="lname" name="lastname" placeholder="Your last name..">
          </div>
        </div>

        <div class="form-3">
          <div class="col-3">
            <label for="lname" class="tel">Phone number</label>
          </div>
          <div class="ph-3">
            <input type="tel" id="telNo" name="telNo" placeholder="Your phone number...">
          </div>
        </div>

      <div class="btn">
          <input type="submit" id="submit" value="Submit">
        </div>
      </form>

这是PHP代码:

<?php

//Store form data in date.csv 
if ( isset( $_POST['submit'] ) ) {

//collect form data
$fname = isset( $_POST['fname'] ) ? $_POST['fname'] : '';
$lname = isset( $_POST['lname'] ) ? $_POST['lname'] : '';
$phone = isset( $_POST['telNo'] ) ? $_POST['telNo'] : '';

//check name is set
if ( $fname == '' ) {
    $error[] = 'First name is required';
}

if ( $lname == '' ) {
    $error[] = 'Last name is required';
}

//check for a valid phone number
$pattern = '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4})$/';
if ( ! preg_match( $pattern, $phone ) ) {
    $error[] = 'Please enter a valid phone number';
}


//if no errors carry on
if ( ! $errors ) {
    # Title of the CSV
    $header = "FName,LName,Phone\n";
    //set the data of the CSV
    $data = "$fname,$lname,$phone\n";

    # set the file name and create CSV file
    $FileName = __DIR__ . "/formdata-" . date( "d-m-y-h-i-s" ) . ".csv";
    if ( file_exists( __DIR__ . $FileName ) ) {
        //we only need header once
        file_put_contents( $FileName, $data, FILE_APPEND );
    } else {
        //add csv header
        file_put_contents( $FileName, $header . $data );
    }

}

$error_message = '';
//if their are errors display them
if ( $errors ) {
foreach ( $errors as $error ) {
    $error_message .= "<p style='color:#ff0000'>$error</p>";
}
}

2 个答案:

答案 0 :(得分:0)

发现错误和建议:

  • include 'php/form.php'之后你有一个不属于那里的逗号并抛出错误:Parse error: syntax error, unexpected ',' in [....].php on line 1
  • 将“form.php”重命名为“create-csv.php”,因为它更具意图揭示名称。阅读Clean, high quality code
  • 更改提交策略:假设包含html表单的文件名为“index.php”。然后通过设置action=""使表单的操作成为一个empy字符串。这意味着表单将被提交到它所在的页面,例如到“index.php”。这样,因为您将“create-csv.php”包含在“index.php”中,您将能够访问“index.php”中“create-csv.php”范围内的所有变量。例如,您将能够访问“index.php”中的$errors数组(已定义并填写“create-csv.php”)。
  • 表单的方法必须是POST。因此,在表单的操作中,设置属性method="post"。始终在表单标记中设置方法属性。
  • 您错过了if (isset($_POST['submit'])) {...}声明的结束}。
  • “提交”按钮必须包含name="submit"属性才能被if (isset($_POST['submit'])) {...}声明识别。
  • 您有$errors,还有$error。设为$errors,因为数组包含多个错误项。注意细节。特别是关于变量,函数名称的那些。
  • 不要从php代码打印html代码。直接在html代码中显示div容器(css​​类“errors”)中的错误。
  • 在第一个名称的输入中:将name="firstname"替换为name="fname"
  • 在姓氏输入中:将name="lastname"替换为name="lname"
  • 在手机标签中:将for="lname"替换为for="telNo"
  • 为了检查是否有任何错误,您必须检查是否存在$errors。因此,请使用if ($errors) {...},而不是使用if (isset($errors)) {...}。使用if ($errors) {...},您只是在检查空虚。
  • 不要在PHP评论中使用“#”,而对于单行使用“//”,对于多行注释不要使用/ * ... * /。
  • $FileName替换为$fileName。在PHP代码中对变量和函数名称使用此“camelCase”命名约定。
  • if (file_exists(__DIR__ . $fileName)) {...}替换为if (file_exists($fileName)) {...},因为__DIR__已预先填充到变量$fileName

以下是工作代码。在其中搜索字符串“@todo”并相应地执行操作。实际上只有一个,在“create-csv.php”中。

请注意,我没有使用正确的电话号码进行测试,因为我没有时间解码您正在使用的电话号码格式。给用户(像我一样)提示数字的外观。

祝你好运。

的index.php:

<?php
/*
 * ================
 * Error reporting.
 * ================
 */
error_reporting(E_ALL);
ini_set('display_errors', 0); // SET IT TO 0 ON A LIVE SERVER !!!

/*
 * ==================================================================
 * Execute operations upon form submit (store form data in date.csv).
 * ==================================================================
 */
include 'php/create-csv.php';
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>
    </head>
    <body>
        <div class="formme">
            <form action="" method="post">
                <?php
                /*
                 * Display all errors if any.
                 */
                if (isset($errors)) {
                    ?>
                    <div class="errors">
                        <?php
                        foreach ($errors as $error) {
                            ?>
                            <p style="color:#ff0000">
                                <?php echo $error; ?>
                            </p>
                            <?php
                        }
                        ?>
                    </div>
                    <?php
                }
                ?>

                <div class="form-1">
                    <div class="col-1">
                        <label for="fname" class="fname">First name</label>
                    </div>
                    <div class="ph-1">
                        <input type="text" id="fname" name="fname" placeholder="Your name..">
                    </div>
                </div>

                <div class="form-2">
                    <div class="col-2">
                        <label for="lname" class="lname">Last name</label>
                    </div>
                    <div class="ph-2">
                        <input type="text" id="lname" name="lname" placeholder="Your last name..">
                    </div>
                </div>

                <div class="form-3">
                    <div class="col-3">
                        <label for="telNo" class="tel">Phone number</label>
                    </div>
                    <div class="ph-3">
                        <input type="tel" id="telNo" name="telNo" placeholder="Your phone number...">
                    </div>
                </div>

                <div class="btn">
                    <input type="submit" name="submit" id="submit" value="Submit">
                </div>
            </form>
        </div>
    </body>
</html>

create-csv.php(文件夹“php”):

<?php

/*
 * ==================================================================
 * Execute operations upon form submit (store form data in date.csv).
 * ==================================================================
 */
if (isset($_POST['submit'])) {
    // Collect the form data.
    $fname = isset($_POST['fname']) ? $_POST['fname'] : '';
    $lname = isset($_POST['lname']) ? $_POST['lname'] : '';
    $phone = isset($_POST['telNo']) ? $_POST['telNo'] : '';

    // Check if first name is set.
    if ($fname == '') {
        $errors[] = 'First name is required';
    }

    // Check if last name is set.
    if ($lname == '') {
        $errors[] = 'Last name is required';
    }

    // Validate the phone number.
    $pattern = '/^(?:\(\+?44\)\s?|\+?44 ?)?(?:0|\(0\))?\s?(?:(?:1\d{3}|7[1-9]\d{2}|20\s?[78])\s?\d\s?\d{2}[ -]?\d{3}|2\d{2}\s?\d{3}[ -]?\d{4})$/';
    if (!preg_match($pattern, $phone)) {
        $errors[] = 'Please enter a valid phone number';
    }

    // If no errors carry on.
    if (!isset($errors)) {
        // The header row of the CSV.
        $header = "FName,LName,Phone\n";
        // The data of the CSV.
        $data = "$fname,$lname,$phone\n";

        /*
         * The file name of the CSV.
         * 
         * NB: __DIR__ describes the location in which this file resides.
         * To go up one level use "dirname(__DIR__)".
         * 
         * NB: You will not be able to append data to an existing file if you use time components 
         * (hour, minutes, seconds) inside the file name. Imagine that you are creating a file 
         * right now, at 12:18:43 o'clock. Then the file will be named "formdata-09-01-18-12-38-43.csv".
         * One second later you will not be able to append data to it because the time will be "12:38:44".
         * Then a new file "formdata-09-01-18-12-38-44.csv" will be created.
         * 
         * I suggest using only the date whithout the time in the file name.
         * 
         * @todo Read the comment above!
         */
        $fileName = dirname(__DIR__) . "/formdata-" . date("d-m-y-h-i-s") . ".csv";

        /*
         * Create the CSV file.
         * If file exists, append the data to it. Otherwise create the file.
         */
        if (file_exists($fileName)) {
            // Add only data. The header is already added in the existing file.
            file_put_contents($fileName, $data, FILE_APPEND);
        } else {
            // Add CSV header and data.
            file_put_contents($fileName, $header . $data);
        }
    }
}

答案 1 :(得分:0)

您不需要包含文件'php / form.php'。您没有捕获数据,因为您没有在表单中指定方法。只需将表单更改为

即可

<form action="php/form.php" method="post">

你的好消息。