使用for循环将变量添加到数据库

时间:2016-12-07 17:26:13

标签: php mysql sql database loops

我的主要问题是为什么PDO :: exec不会执行我的循环的每次迭代,而只是在第一次迭代中执行。

我正在尝试将坐标插入MySQL数据库。

我的数据库结构是(数字(主键),x,y,z)。

我要求用户插入一个数字($ n),然后让他们填写$ n套坐标。

用户输入传递到另一个带有$ _POST的页面,然后由动态变量名称检索并插入到数据库中。

一切正常,除了循环只在第一次迭代时写入数据库。所以我最终得到了x1,z1,y1的结果,但没有别的。

任何人都可以解释我做错了什么(不使用数组)?

<?php
require_once('db.php');
$n = $_POST['selectOption'];

for($i = 1; $i < $n+1;$i++){
    ${'x' . $i} = $_POST["x" . $i];
    ${'y' . $i} = $_POST["y" . $i];
    ${'z' . $i} = $_POST["z" . $i];

    $rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
              VALUES ('$n', '${'x' . $i}', '${'y' . $i}', '${'z' . $i}')");
}
?>

这是我的表格

<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
        <?php
            for($i = 0; $i < $n; $i++)
            {
        ?>
          x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>

    <?php 
        }
    ?>
    <br>
    <input type="hidden" name="selectOption" value="<?php echo $n;?>">
    <input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>

3 个答案:

答案 0 :(得分:1)

 require_once('aaron_stockdale_database.php');
 $n = $_POST['selectOption'];

for($i = 1; $i < $n+1;$i++){
  $x = $_POST["x" . $i];
  $y = $_POST["y" . $i];
  $z = $_POST["z" . $i];

$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
          VALUES ('$n', '$x', '$y', '$z')");
}

剩下的就在你身上;)

并且还检查是否有任何字段是主键,这将阻止插入两次。

答案 1 :(得分:0)

由于您的问题已经收到了可接受的答案,我想向您提供有关您的HTML代码的提示。

<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>

<?php 
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>

现在,这段代码可以清理一下。

<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
echo 'x' . $i+1 . '<input name="x' . $i+1 . '" type=text>, y' . $i+1 . ' <input name="y' . $i+1. '" type=text>, z' . $i+1 . '<input name="z' . $i+1 . '" type=text><br>'
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" value="Submit">
</form>

我将“oonClick”更改为“onClick”,然后我将其删除,就像您提交时一样,您无需导航,因为浏览器会在提交时执行此操作。 然后我删除了重复打开和关闭php标签,并将所有回声合并为一个。

答案 2 :(得分:-1)

这是我在一个文件中的解决方案:

<!DOCTYPE html>
<html lang=en>
  <head>
    <script>
      function validcoord(e) {
        var key;
        var keychar;

        if (window.event)
          key = window.event.keyCode;
        else if (e)
          key = e.which;
        else
          return true;
        keychar = String.fromCharCode(key);
        keychar = keychar.toLowerCase();

        // control keys
        if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
          return true;

        // Numeral Characters
        else if ((("0123456789-.,").indexOf(keychar) > -1))
          return true;
        else
          return false;
      }
    </script>
    <style>
      input[type="number"] { text-align: right; width: 50px; }
      label { margin-left: 4em; }
    </style>
  </head>
  <body>
    <?php
      define ("SELF", $_SERVER['PHP_SELF']);
      define ("EOL", "\r\n");
      // Modify as needed
      define ("MINNUMCORDS" ,  "1");
      define ("MAXNUMCORDS" , "10");
      define ("DFLTNUMCORDS",  "2");

      $formSubmitted = (empty($_POST)) ? FALSE : TRUE;

      if (!$formSubmitted) {
        $htmlOutput = '
          <form action="' . SELF . '" method=post name=foo id=foo>
            <input type=hidden name=current value=0>
            <label>Enter the number of Coordinates:
            <input type=number autofocus onFocus="this.select()"' .
                  ' min=' . MINNUMCORDS . 
                  ' max=' . MAXNUMCORDS . 
                ' value=' . DFLTNUMCORDS .
                 ' name=numcords /></label>
          </form>' . EOL;
          echo $htmlOutput;
      } // end if not submitted
      else { // a form HAS been submitted

        foreach ($_POST as $key => $value) { $$key = $value; }
        unset($_POST);

        if (!empty($coord)) { // We got some input that may be a valid x,y,z coordinate
          if ( substr_count($coord, ",") != 2 ) {
            $error = "We're looking for THREE numbers seperated by TWO commas.";
          } // end  if we don't have three values
          else { // We got three Values
            $coord = trim($coord);
            list($x,$y,$z) = explode(",", $coord);
            if ( !(is_numeric($x) && is_numeric($y) && is_numeric($z)) ) {
              $error = "We're looking for three VALID NUMBERS seperated by two commas.";
            } // end if all three numbers are not valid
            else { // We got three Values and each of them are numbers
              require('db.php');
              $rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
                  VALUES ('$numcords', '$x', '$y', '$z')"); 
              //echo "INSERT INTO coordinate3d (number,x,y,z) VALUES ('$numcords', '$x', '$y', '$z')<br />" . EOL;
            } // end three valid numbers
          } // end three values
        } // end if we have some input in $coord

        if ($error) {
          echo "~~ " . $error . "<br /><br />" . EOL;
          --$current;
        } // end if error

        if ( $current < $numcords ) {
          $htmlOutput  = 'Please enter the coordinate in the form: x,y,z (Ex: -.4,2,8.5)' . EOL;
          $htmlOutput .= '<form action="' . SELF . '" method=post name=bar id=bar>' . EOL;
          $htmlOutput .= '  <input type=hidden name=numcords value="' . $numcords . '" />' . EOL;
          $htmlOutput .= '  <input type=hidden name=current value="' . ++$current . '" />' . EOL;
          $htmlOutput .= '  <label>Coord #' . $current . ': ';
          $htmlOutput .=   '<input type=text name=coord size=12 maxlength=48 ' .
                              'autofocus onKeyPress="return validcoord(event);" /></label>' . EOL;
          $htmlOutput .= '</form>' . EOL;
          echo $htmlOutput;
        } // end if we need to get another coord
      } // end form was submitted
    ?>
  </body>
</html>