存储动态创建的文本字段的输入

时间:2013-07-04 22:10:39

标签: php javascript mysql database forms

我创建了一个按钮,可以在每次点击时创建名称= 1,2,3 ...的文本。我想将这些文本字段的所有输入存储在数据库中。

<?php 
    $con = mysqli_connect("localhost", "root","", "abc");

    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $maxoptions = 10;

    // I don't want only 10 inputs from text fields 
    // but as many as the user creates and fills
    for ($i = 1; $i < $maxoptions; $i++) {
        $sql="INSERT INTO qa (q, a$i)
        VALUES
        ('$_POST[q1]', '$_POST[i]')";
        // '$_POST[i]' is not working
    }

    if (!mysqli_query($con, $sql))
    {
      die('Error: ' . mysqli_error($con));
    }

    mysqli_close($con);

?>

现在,如何使用这些文本字段动态创建数据库中的列?

以下是我用于创建文本字段的JavaScript代码:

var intTextBox1 = 0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement1()
{
    intTextBox1 = intTextBox1 + 1;
    var contentID = document.getElementById('content1');
    var newTBDiv = document.createElement('div');
    newTBDiv.setAttribute('id','strText'+intTextBox1);
    newTBDiv.innerHTML = "Option" + intTextBox1 + 
      ": <input type='text' id='" + intTextBox1 + 
      "'    name='" + intTextBox1 + "'/>";
    contentID.appendChild(newTBDiv);
}

//FUNCTION TO REMOVE TEXT BOX ELEMENT
function removeElement1()
{
    if (intTextBox1 != 0)
    {
        var contentID = document.getElementById('content1');
        contentID.removeChild(document.getElementById('strText'+intTextBox1));
        intTextBox1 = intTextBox1 - 1;
    }
}

这是按钮的代码:

<form id="s1form" name="s1form" method="post" action="qno1.php">
    <input type="text" name="q1">
<input type="button" value="Add a choice" onClick="javascript:addElement1();" />
    <input type="button" value="Remove a choice" onClick="javascript:removeElement1();" />
    <div id="content1"></div>

1 个答案:

答案 0 :(得分:0)

这是我的2美分:首先开始回显文本字段和按钮

<?php
$columns=10; //we'll start off with 10
for($i=0; $i<$columns; $i++){
    echo "<input type=\"text\" id=\"$i\" name=\"$field_i\">";
}
//the placeholder for the next element
echo "<div id=\"newfield\"></div>";
//and the buttons
echo "<input type=\"button\" value=\"Add Field\" onclick=\"addfield()\">";
echo "<input type=\"button\" value=\"Remove Field\" onclick=\"removefield()\">";

接下来继续JS脚本

<script type="text/javascript">
<?php echo "fields=".$columns-1 .";"; /*from before, mind the off-by-one*/ ?>
function addfield(){
    elm=document.getElementById("newfield");
    //construct the code for new field
    nf="<input type=\"text\" name=\"field_"+ fields +"\">";
    nf+="<div id=\"newfield\"></div>"; //placeholder for next field
    elm.innerHTML=nf;
}

function removefield(){
    (elem=document.getElementById(fields)).parentNode.removeChild(elem);
    fields--;
}
</script>

我找到了删除元素in this answer的代码。

我对使用+进行连接有一些保留意见,如果您遇到任何问题,请使用.append()

现在检查你的结果(因为我没有使用数组作为GET请求)我们做了一些黑客攻击:

//php
$i=0;
while(isset($_GET["field_".$i])){
    $new_cols[$i]=$_GET["field_".$i];
    $i++;
}
addColumns($new_cols)

其中addColumns()只是adds new columns to the database有时候我会发现isset()有点气质,如果它没有削减$_GET["field_".$i]!==false

用于创建新列的SQL代码非常简单,它只是一个PHP循环,所以我不会在这里编写函数。希望有所帮助。

编辑:您可以通过两种方式执行添加列功能:

首先,MySQL代码如下:

ALTER TABLE Persons
ADD DateOfBirth date

其中DateOfBirth是列的名称,date是其数据类型。因此,使用从前面的代码获得的列名称数组,一种方法是顺序执行查询:

addColumns($names){
    $sql="ALTER TABLE (your table) ADD ";
    for($i=0; $i<count($names); $i++){
        if(sanitize($names[$i])===$names[$i])
            mysqli_query($sql.sanitize($names[$i])." (datatype)");
        else{
            //something fishy is going on, report the error
            die("error");
        }
    }
}

其中sanitize()是一个正确的SQL输入卫生功能。请注意,我不只是转义输入,我中止以防转义字符串和原始字符串不匹配

第二种方法是在单个查询中连接所有列。试试两者,看看哪些有效。为了做到这一点,我将从上面修改for循环

$sql="ALTER TABLE (your table) ";
    for($i=0; $i<count($names); $i++){
        if(sanitize($names[$i])===$names[$i])
            $sql.="ADD ".$names[$i]." (datatype),"; //notice the comma
        else{
            //something fishy is going on, report the error
        }
    }
//remove the comma from the last concatenation. There might be an off-by-one in this,
//depends if strlen also counts the NULL character at the end
$sql[strlen($sql)]='\0';
//execute the query
mysqli_query($sql);

请注意,您可能需要将列名称包装在奇怪的字符中,例如`或'。我有一段时间没有使用MySQL,所以我不记得那个的确切语法。

相关问题