0

有人可以帮我吗,我有一个带有 2 个文本区域的表格,用于名称和用户名。我在这里尝试的是我想同时插入带有用户名和姓名的人员列表,因此我包含来自 jquery 的函数来复制这两个字段。

例如:在我输入的表格上:

name      username
1.john      john      
2.carl      carl123

提交后这是我得到的:

name       username
1.john        john123
2.john        carl123
3.carl        john123
4.carl        carl123

这是代码:

<?php
require_once "connect_to_mysql.php"; 
if($_POST['name'] || $_POST['username'])
    {

        $array=$_POST['name'];
        $array2=$_POST['username'];

        foreach($array as $name) 
            foreach($array2 as $username) 
            {
                if(strlen($name)>0)
                    {
                        echo '<h3>'.$name.'<h3/>';
                        {
                            {
                                if(strlen($username)>0)
                                    {
                                        echo '<h3>'.$username.'<h3/>';
                                        $sqlCommand = "INSERT INTO test(name, username) VALUES ('$name', '$username')";
                                        $query = mysql_query($sqlCommand) or die (mysql_error());
                                    }}}
                    }
            }
    }

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>Jquery Duplicate Fields Submit Form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript" src="http://ajax.googleapis.com/
                                        ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="reCopy.js"></script>
    <script type="text/javascript">
      $(function(){
      var removeLink = ' <a class="remove" href="#"         onclick="$(this).parent().slideUp(function(){ $(this).remove() }); return        false">remove</a>';
      $('a.add').relCopy({ append: removeLink});    
      });
    </script>
    <style type="text/css">
      body{ font-family:Arial, Helvetica, sans-serif; font-size:13px; }
      .remove {color:#cc0000}
      .input{ border: solid 1px #006699; padding:3px}

    </style>
  </head>

  <body>

    <div style="background-color:#ffffcc; padding:4px; border:#333 1px solid">9lessons programming Blog. Topics focused about jquery, ajax, mysql, php and java. <a href="http://9lessons.info">http://9lessons.info</a></div>
    <form method="post" action="">
      <p class="clone"> <input type="text" name="name[]" class='input'/> 
        <input type="text" name="username[]" class='input' id="username[]"/>
      </p>
      <p><a href="#" class="add" rel=".clone">Add More</a></p>
      <input type="submit" value=" Submit " />
    </form>
  </body>
</html>
4

1 回答 1

0

问题是您正在嵌套循环:

foreach ($array as $name)
    foreach ($array2 as $username)

所以它将生成所有名称和用户名的叉积。您应该使用一个循环同时遍历两个数组:

foreach ($array as $i => $name) {
    $username = $array2[$i];
    ...
}
于 2013-09-19T01:53:20.293 回答