【问题标题】:how to save the data that the user input in form page after the script executed?脚本执行后如何保存用户在表单页面中输入的数据?
【发布时间】:2013-12-26 14:39:53
【问题描述】:

我可以知道是否可以从用户之前输入的表单中保存数据?

这是表格文件:

    <!DOCTYPE HTML>
    <html>
    <head>
        <meta http-equiv="content-type" content="text/html" />        
        <title>Data</title>
        <style type="text/css">
        input {
            background-color: #999;
            border-style: solid;
            border-color: #999;
            border: 0px 4px 0px 4px;
            padding: 3px 6px 3px 6px;
            margin: 10px 0;
        }
        input:focus {
            border-style: solid;
            border-color: black;
        }
        </style>
    </head>

    <body>

    <form action="count.php" method="post" action="post">
    Name: <input type="text" name="customername" /><br />
    DOB: <input type="text" name="date" /> <input type="text" name="month" /> <input type="text" name="year" /><br />
    First Row: <input type="text" name="rowone" /><br />
    Second Row: <input type="text" name="rowtwo" /><br />
    Third Row: <input type="text" name="rowthree" /><br />
    <input type="submit" value="Go" />
    </form>

    </body>
    </html>

这里是执行用户输入的表单数据的php。

 <?php
    $cname = $_POST['customername'];
    $dob_date = $_POST['date'];
    $dob_month = $_POST['month'];
    $dob_year = $_POST['year'];
    $year = gmdate("Y");
    $month = gmdate("m");
    $day = gmdate("d");
    $age = $year - $dob_year; // $age calculates the user's age determined by only the year
    if ($month < $dob_month) { // this checks if the current month is before the user's month of birth
        $age = $age - 1;
    } else if (
            $month == $dob_month && $day >= $dob_date) { // this checks if the current month is the same as the user's month of birth and then checks if it is the user's birthday or if it is after it
        $age = $age;
    } else if ($month == $dob_month && $day < $dob_date) { //this checks if the current month is the user's month of birth and checks if it before the user's birthday
        $age = $age - 1;
    }

    //add all initial data into an matrix variable for easier access to them later
    //To access rowone use $rows[0][0], rowtwo $rows[1][0] ect.
    //The matrix is an array which contains multiple array. eg. 2-dimensional arrays
    //To get all the variables with $r1X simply retrieve the first array of the matrix eg $rows[0]
    $rows = array(array($_POST['rowone']), array($_POST['rowtwo']), array($_POST['rowthree']), array());

    //Similarities between row1 and row2 made me incoporate modulo value as an argument.
    function incmod($a, $m) {
        return ($a % $m) + 1;
    }

    //Population each row, with $populationCount number of elements, where each element is added with incmod(X, $mod)
    function populateRow($rowId, $populationCount, $mod) {
        //The global keyword is needed in order for the function to access the global variable.
        global $rows;
        $row = $rows[$rowId];
        while (sizeof($row) < $populationCount) {
            $rowInd = sizeof($row) - 1;
            $m = incmod($row[$rowInd], $mod);
            array_push($row, $m);
        }

        //Due to how php works with variables and references we need to set the row back into the global variable.
        $rows[$rowId] = $row;
    }

    //This function makes sure that the values allways are between 1 and 12.
    function bindToRange($v) {
        if ($v == 0)
            return 1;
        return ($v - 1) % 12 + 1;
    }

    //Population the first three rows
    populateRow(0, 7, 7);
    populateRow(1, 12, 12);
    populateRow(2, 12, 12);

    //Creating the forth row by nested forloops.
    //The first loop iterates over the entries in a row (in your example this would be the letters e.g r1a r1b ect)
    //The second (inner) loop iterates of the rows (in you example this would be the number you had in your variables.)
    //The sum over each of the three rows are added, then bound to 1-12 range, before being added to the forth row.
    for ($cId = 0; $cId < 7; $cId++) {
        $sum = 0;
        for ($rId = 0; $rId < 3; $rId++) {
            $sum += $rows[$rId][$cId];
        }
        array_push($rows[3], bindToRange($sum));
    }

    //Same as above, but for the last two remaining values. Should give a total of nine entries in the forth row.
    for ($cId = 7; $cId < 12; $cId++) {
        $sum = 0;
        for ($rId = 1; $rId < 3; $rId++) {
            $sum += $rows[$rId][$cId];
        }
        array_push($rows[3], bindToRange($sum));
    }

    function lower_than_2($var){
        return ($var > 1);
    }
    $cssClassName = "match";

    // array_count_values will count how many times each value is in the array
    $cssBase = array_count_values($rows[3]);
    // remove from array values that are lower than 2
    $cssBase = array_filter($cssBase, "lower_than_2");

    $cssNumber = array();
    $cssCounter = 1;
    // make $cssNumber be a mirror of $cssBase (same keys), but with serial values
    foreach ($cssBase as $key => $value) {
        $cssNumber[$key] = $cssCounter;
        $cssCounter++;
    }
    unset($cssCounter);
    // ------------------------------------------------

    ?>
    <!DOCTYPE HTML>
    <html>
        <head>
            <meta http-equiv="content-type" content="text/html" />
            <title>Result</title>
            <link rel="stylesheet" type="text/css" href="./css/style.css" />
        </head>

        <body>
            Customer Name: <?php echo $cname; ?><br />
            DOB: <?php echo $dob_date; ?> / <?php echo $dob_month; ?> / <?php echo $dob_year; ?><br />
            <b><?php echo $age; ?></b> Years Old
            <table>
                <?php
                //Instead of listing up (hard-coded) I've used nested forloops to generate the html.
                //The loops are similar to the ones above, but use sizeof keyword to figure out how many iterations it needs.

                $lines = sizeof($rows)+1; // $rows have 4 rows, we will need 1 more
                for ($rId = 0; $rId < $lines; $rId++) {
                    echo "<tr>\n";

                    if($rId < 3){
                        $row = $rows[$rId];
                        $rowSize = sizeof($row);

                        for ($cId = 0; $cId < $rowSize; $cId++) {
                            echo "<td>" . $row[$cId] . "</td>\n";
                        }
                    } else if($rId == 3){
                        $row = $rows[$rId];
                        $rowSize = sizeof($row);

                        for ($cId = 0; $cId < $rowSize; $cId++) {
                            echo "<td"; // open td
                            // if the value is in cssBase array, we will apply a css class
                            if(array_key_exists($row[$cId], $cssBase))
                                echo ' class="'. $cssClassName . $cssNumber[$row[$cId]] .'"';
                            echo ">"; // close td
                            echo $row[$cId];
                            echo "</td>\n";
                        }
                    } else if($rId == 4){
                        for ($cId = 0; $cId < 12; $cId++) {
                            if($cId == (($age-1)%12)){
                                echo '<td>'. "$age Years Old" .'</td>'."\n";
                            } else {
                                echo "<td></td>\n";
                            }
                        }
                    }
                    echo "</tr>\n";
                }

    // ------------------------------------------------

                ?>
            </table><br /><br />
            <a href="./" target="_blank" title="Calculate Again">Calculate Again</a>

        </body>
    </html>

是否可以在 count.php 页面上添加一个保存按钮,并且该值将是用户在表单页面中之前键入的值。并且保存按钮将回显“数据已保存”,或者如果存在,它将在同一页面中回显“数据已存在”。如果是,我需要使用什么方法?当我搜索谷歌时,我是全新的,我找不到我需要的确切答案。我已经在 mysql 中创建了表来存储数据。

我要存储的数据是出生日期、第一行、第二行和第三行。 在mysql中创建表,dob为日期,rowone,rowtwo和rowthree为varchar(255),id为int(11)。

这是我的 insertdata.php

  <?php

    $dbhost = "localhost";

    $dbuser = "root";

    $dbpass = "";

    $dbname = "mama";

    class dob {
        public function set_dob($dob_date, $dob_month, $dob_year) {
            $this->dob = $dob_date.'/'.$dob_month.'/'.$dob_year;
        }
    }

    $con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
    $sql="INSERT INTO profile (dob,rowone,rowtwo,rowthree) VALUES ('$_POST[dob]','$_POST[rowone]','$_POST[rowtwo]','$_POST[rowthree]')";

    if (!mysqli_query($con,$sql))
      {
      die('Error: ' . mysqli_error($con));
      }
    echo "1 record added";

    /* close connection */
    $mysqli->close();
    ?>

并显示如下错误: 注意:未定义索引:第 18 行 C:\xampp\htdocs\mama\inc\insertdata.php 中的 dob

注意:未定义索引:第 18 行 C:\xampp\htdocs\mama\inc\insertdata.php 中的 rowone

注意:未定义索引:第 18 行 C:\xampp\htdocs\mama\inc\insertdata.php 中的 rowtwo

注意:未定义的索引:第 18 行 C:\xampp\htdocs\mama\inc\insertdata.php 中的 rowthree 添加了 1 条记录 注意:未定义变量:第 27 行 C:\xampp\htdocs\mama\inc\insertdata.php 中的 mysqli

致命错误:在第 27 行调用 C:\xampp\htdocs\mama\inc\insertdata.php 中非对象的成员函数 close()

【问题讨论】:

    标签: php jquery mysql forms


    【解决方案1】:

    要存储从你的视图页面发送的数据,我认为你需要先在你的count.php中建立你的应用程序和你的数据库MySQL之间的连接,然后创建一个方法来存储你的数据。

    您可能想查看此链接:

    http://www.w3schools.com/php/php_mysql_insert.asp

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      有很多方法可以做到这一点...使用可以使用 AJAX 调用进行验证的客户端库(jQuery、AngularJS、DOJO...等),或者如果您想将纯 html 与 php 一起使用,您可以使用类似的东西:

      <form action="count.php" method="post" action="post">
      Name: <input type="text" name="customername" value="<?php echo $prevCName; ?>" /><br />
      DOB: <input type="text" name="date" value="<?php echo $prevDate; ?>" /> <input type="text" name="month" value="<?php echo $prevMonth; ?>" /> <input type="text" name="year" value="<?php echo $prevYear; ?>" /><br />
      First Row: <input type="text" name="rowone" value="<?php echo $prevROne; ?>" /><br />
      Second Row: <input type="text" name="rowtwo" value="<?php echo $prevRTwo; ?>" /><br />
      Third Row: <input type="text" name="rowthree" value="<?php echo $prevRThree; ?>" /><br />
      <input type="submit" value="Go" />
      </form>
      

      这个表单文件必须是一个 php 文件,并且你应该确保之前的值被保存在......在 $_SESSION 或......在以前的文件中使用包含......需要......等等。

      【讨论】:

      • 但是我如何用我当前的代码做到这一点?我有点新,卡在这里,一切都设置好只需要保存在数据库中
      【解决方案3】:

      最后你只想做以下事情:

      $con=mysqli_connect($host,$user,$password,$db);
      $sql = "INSERT INTO tablename (dob,rowone,rowtwo,rowthree)
      VALUES (".$_POST['customername'].",".$_POST['date'].",".$_POST['month'].",".$_POST['year'].");"
      mysqli_query($con,$sql);
      

      我在我的示例中使用 mysqli。更好的方法当然是 PDO:http://tw1.php.net/manual/en/book.pdo.php

      最终,您当然会需要安全性,因此您将使用准备好的语句:http://php.net/manual/en/pdo.prepared-statements.php

      【讨论】:

      • 我添加了错误代码,介意看看我哪里出错了?但没有数据添加到数据库中
      • 应该是:$sql="INSERT INTO profile (dob,rowone,rowtwo,rowthree) VALUES ($_POST[dob],$_POST[rowone],$_POST[rowtwo],$_POST[rowthree])";$sql="INSERT INTO profile (dob,rowone,rowtwo,rowthree) VALUES (". $_POST[dob].",".$_POST[rowone].",".$_POST[rowtwo].",".$_POST[rowthree].")"; 假设 $_POST[rowone] 存在。不确定这是您要使用的变量还是应该是$_POST['rowone']
      • 我在上一条评论中打错了字。您正在尝试在 $_POST[] 变量中获取第一个项目。例如,虽然您想要键为“rowone”的元素。您在 $_POST['rowone'] 等变量中缺少撇号。
      【解决方案4】:

      也许你可以通过使用 find('first') 或 find('all') 得到你想要的。

      $ex = $this->find('first' , array(
       'condition' => array ('model_name.id' => 22 //specific id
      )));
      

      您可以从具有特定位置 (id) 的表中获取任何值。 更清楚地说,例如:第 i 行第 j 列的元素。

      【讨论】:

        【解决方案5】:

        查看错误堆栈跟踪,您的 php 代码中有 2 个错误:

        1. 第 18 行:您没有使用字符串来访问 $_POST 数据。使用 $_POST['rowone'], $_POST['rowtwo']... 代替 $_POST[rowone], $_POST[rowtwo]...
        2. 第 27 行:当您使用程序 mysqli 时,要关闭连接,您必须使用 mysqli_close($con) 而不是 $mysqli->close()

        我会这样做:

            try {
                // Create connection
                $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
        
                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                }
                $insertSQL = "INSERT INTO profile (dob, rowone, rowtwo, rowthree) VALUES (?, ?, ?, ?)";
                $stmt = $conn->prepare($insertSql);
                $stmt->bind_param("ssss", $_POST[dob], $_POST[rowone], $_POST[rowtwo], $_POST[rowthree]); // the four "s" are used to indicate the 4 strings to be set in the parametric query
        
                if ($stmt->execute() === false) {
                    $errMsg = "";
                    foreach (mysqli_errors() as $error) {
                        $errMsg.= "SQLSTATE: ".$error[ 'SQLSTATE']." - ";
                        $errMsg.= "code: ".$error[ 'code']." - ";
                        $errMsg.= "message: ".$error[ 'message']."\n";
                    }
                    throw new Exception($errMsg);
                }
            } catch (Exception $e) {
                error_log("Error during saving record: ".$e->getMessage());
            } finally {
                $stmt->close();
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-02-17
          • 2013-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-01
          • 1970-01-01
          相关资源
          最近更新 更多