如何将多个文本框值添加到数据库中?

时间:2014-03-17 17:21:21

标签: php

我正在构建一个脚本,当我点击“添加”时,它会再出现一个框,当我点击“删除”时,它会删除我创建的最后一个框。

代码工作正常,但我想将这些文本框中的信息添加到我的数据库中,我不能这样做,因为我的php脚本只读取第一个文本框。

我只想在提交时添加所有信息

如何将多个文本框值添加到我的数据库中?

<html>
<head>
<title>
</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript"><!--


    $(document).ready(function(){

    var counter = 2;
    $("#add").click(function () {
    if(counter==11){
        alert("Too many boxes");
        return false;
    }   
        $("#textBoxes").append("<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input     type='textbox' id='t"+counter+"' > </div>\n");
        ++counter;
    });

    $("#remove").click(function () {
    if(counter==1){
        alert("No boxes");
        return false;
    }   
        --counter;
        $("#d"+counter).remove();
    });
  });
// --></script>


</head><body>

 <div id='textBoxes'>
 <form method="POST">
<div id='d1' ><label for="t1"> Textbox 1</label><input name="nome" type='textbox' id='t1' ></div>
</div>
<input type='button' value='add' id='add'>
<input type='button' value='remove' id='remove'>
<input type='submit' name="adicionar" value='adicionar'>

</form>

<?php

 $dbHost = 'localhost';
            $dbUsername = 'hr';
            $dbPassword = '';
            $dbDatabase = 'r_inserir';

            $db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
            mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");

if(isSet($_POST['adicionar']))
{

$nome=mysql_real_escape_string($_POST['nome']);

$sql=  mysql_query("INSERT INTO registos(nome) values ('".$nome."')");
}
?>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

只需编辑您的sql语句以包含更多数据。

$nome=mysql_real_escape_string($_POST['nome']);
$snome=mysql_real_escape_string($_POST['snome']);

$sql=  mysql_query("INSERT INTO registos(nome,snome) values ('".$nome."','".$snome."')");

首先需要确保您的数据库还有这些额外的列。

然后只需在HTML中添加另一个框

<input name="snome" type="textbox">

答案 1 :(得分:0)

    You need to give the same name to all the input boxes.  In your code it would be:
      name="nome"

    I notice that you are giving different id to the input boxes, which is good. But in your dynamically generated input boxes you are missing the name attribute for the input boxes.  Once you have this fixed.

    You could access the input boxes array like this:

    $names = $_POST['nome'];


    foreach( $names as $key => $n ) {
         $name=$n;
//sql query to insert into the db
    }