0

クリックするたびに name=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>
4

1 に答える 1