使用foreach循环传递两个变量

时间:2015-12-22 04:22:29

标签: php jquery mysql foreach

这是一个动态添加文本字段的代码。当我们点击一​​个链接时,它会自动添加文本字段并将数据传递给数据库。但是现在我想要点击链接时输入两个文本字段并传递值database.how我可以实现吗?  代码如下所示

的index.php

 <?php 
    require("dbconn.php");
    ?>

    <html>
    <head>
    <title></title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    var counter = 0;
    $(function(){
        $('p#add_field').click(function(){
            counter += 1;
            $('#container').append(
                    '<strong>Hobby No. ' + counter + '</strong><br />' 
                    + '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
                    +'<input id="field_' + counter + '" name="name[]' + '" type="text" /><br />' );

        });
    });
    </script> 

    <body>

    <?php
    if (isset($_POST['submit_val'])) {
    if ($_POST['dynfields']) {
    foreach ( $_POST['dynfields'] as $key=>$value ) {
    $values = mysql_real_escape_string($value);
    $query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection );  

    }
    }

        echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

        mysql_close();
    }
    ?>
    <?php if (!isset($_POST['submit_val'])) { ?>
        <h1>Add your Hobbies</h1>
        <form method="post" action="">


            <div id="container">
                <p id="add_field"><a href="#"><span>Click To Add Hobbies</span></a></p>
            </div>

            <input type="submit" name="submit_val"  value="Submit"  />
        </form>
    <?php } ?>

    </body>
    </html>

index.php页面中单击添加文本字段将给出动态文本字段。我想添加两个或更多文本字段并希望将值传递给数据库

1 个答案:

答案 0 :(得分:0)

可能是您的mysql连接字符串不正确(如果您通过删除$valuesmysql_real_escape_stringecho "INSERT INTO my_hobbies (hobbies) VALUES ('$value')"作为空白测试替换,并查看这是否是所需的sql字符串。 )。

注意:开始使用mysqli或pdo,因为不推荐使用mysql。

你可以这样试试:

    <?php

        if (isset($_POST['submit_val'])) {
        $mysqli = new mysqli('localhost','root','root','hobby');//make sure your connection is made
        if (mysqli_connect_errno()) {
          echo "Problem in connection";
          exit();
        }
        if ($_POST['dynfields']) {
        foreach ( $_POST['dynfields'] as $key=>$value ) {
        $values = $mysqli->real_escape_string($value);
       // echo $values;
        $sql= "INSERT INTO my_hobbies (hobbies) VALUES ('$values')";
        //echo $sql;
        $mysqli->query($sql);
        if($mysqli->errno > 0){
          echo "PROBLEM WHILE SAVING";
          exit;
         }
        }
        }

            echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

            mysql_close();
        }
        ?>