0

I have made a button which creates a text with name=1,2,3 ... on every click. I want to store all the inputs of these text fields in database.

<?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);

?>

Now, how to create columns in the database dynamically with these text fields?

Here is the JavaScript code with which I am creating the text fields:

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;
    }
}

and here is the code of button:

<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>
icedwater
  • 4,701
  • 3
  • 35
  • 50
  • 1
    Before you write **any** more SQL code, please read up on [proper escaping](http://bobby-tables.com/php) to avoid nasty [SQL injection bugs](http://bobby-tables.com/). You cannot put `$_POST` values into your query string directly. You **must** use the [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) method to properly apply them. – tadman Jul 04 '13 at 22:13
  • possible duplicate of [PHP MySQLi Multiple Inserts](http://stackoverflow.com/questions/1488033/php-mysqli-multiple-inserts) – tadman Jul 04 '13 at 22:35
  • Fire-Dragon-DoL I am not an expert of programming. i am not familiar with AJAX. can i do all of this work with AJAX.? and thankyou very much all of you. THis site is very helpful to me. – Coop Westerner Jul 04 '13 at 22:38
  • @CoopWesterner: Sorry, I completely missed the javascript part in the question, I thought you were trying to call PHP functions from javascript, forgive my comment. – Francesco Belladonna Jul 04 '13 at 22:41
  • Fire-Dragon-DoL no problem. i happens sometime. What about counting the no of text fields which will be created by the user. Of i have to count then how to count. – Coop Westerner Jul 04 '13 at 22:47
  • Are you sure you want to create *columns* and not add a new row? Pardon my question but I've seen many people who say they want to alter their database when in fact they want to add data to it – rath Jul 05 '13 at 01:31

1 Answers1

0

Here's my 2 cents: First off start with echoing the text fields and the button

<?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()\">";

Next continue to the JS script

<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>

I found the code to remove elements in this answer.

I have some reservations about using + for concatenation, if you run into any problems use .append() instead.

Now to check your results (since I didn't use an array for the GET request) we do a bit of a hack:

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

where addColumns() simply adds new columns to the database Sometimes I find isset() a bit temperamental, if it doesn't cut it do $_GET["field_".$i]!==false.

The SQL code for creating new columns is pretty easy and it's just one PHP loop so I won't be writing the function here. Hope that helps.

Edit: You can do the add column function in two ways:

Firstly, the MySQL code is the following:

ALTER TABLE Persons
ADD DateOfBirth date

where DateOfBirth is the name of the column and date its data type. Therefore, using the array of column names obtained from the previous code, one way to do it is by executing the query sequentially:

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");
        }
    }
}

where sanitize() is a proper SQL input sanitation function. Note that I don't just escape the input, I abort in case the escaped string and the original don't match

The second method is to concatenate all columns in a single query. Try both and see what works. In order to do this I'll modify the for loop from above

$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);

Be aware that you may need to wrap column names in weird characters such as ` or ' . I haven't used MySQL in a while so I can't remember the exact syntax on that one.

Community
  • 1
  • 1
rath
  • 3,655
  • 1
  • 40
  • 53
  • Note: I found a bug in my code, then went for a fag, then forgot about it. Tell me if you spot it – rath Jul 05 '13 at 02:10
  • Thanks rath for the answer. i was busy for couple of days. I am going to check this. I'll tell you about the result of your code. – Coop Westerner Jul 07 '13 at 09:53
  • Now that I take another look at it I see there should be a `fields++;` at the end of `addfield()` but I think the bug I mentioned is a different one – rath Jul 07 '13 at 15:06
  • will someone please help me with adding the columns dynamically. What i have to write in the PHP portion of my code. i am not familiar with isset. and what to write in VALUES portion of INSERT in to db... code. – Coop Westerner Jul 07 '13 at 16:20
  • i think there is some problem here `nf=""; // fields is not defined anywhere` – Coop Westerner Jul 07 '13 at 16:25
  • Make sure to embed the JS in a .php file to get the PHP code to run, otherwise if you know in advance how many fields you'll start off with, you can use pure JS `fields=10;` and remove the echo code. – rath Jul 07 '13 at 16:42
  • I need the inputs from the TEXT FIELDS in the rows but if there are only 5 columns and inputs are 10 then how the remaining columns with (e.g. a1, a2...) names can be created dynamically. – Coop Westerner Jul 07 '13 at 16:45
  • You get the inputs from the code snippet that uses the `$_GET[]` variable. You *create* the fields dynamically from JS by amending the `newfield` div's inner HTML with the code of a new text field, *plus* a new `newfield` to accomodate the next addition. – rath Jul 07 '13 at 16:51
  • @ rath Thanks for your effort rath. The Mozilla Firefox browser is showing an error message box pointing that there is some problem in this code `$new_cols[$i]=$_GET["field_".$i];` – Coop Westerner Jul 07 '13 at 18:14
  • yes it was an infinite loop, I corrected it. If it's still complaining the error is probably somewhere in the previous lines – rath Jul 07 '13 at 19:23
  • Following errors now `Undefined variable: new_cols...` `mysqli_query() expects at least 2 parameters, 1 given...` `Undefined index: field_1` What to write here `$sql="INSERT INTO qa (a$i) VALUES ('$f')";` `//this variable is defined by me . i don't know how to put a variable e.g $i in $_get` `$f=$_GET["field_".$i]; ` – Coop Westerner Jul 07 '13 at 21:25
  • The mysqli_query you can [figure out yourself](http://php.net/manual/en/mysqli.query.php). I don't know how you used the code but make sure you understand what's going on before using it. It's very possible I made a mistake somewhere (it is after all the lengthiest answer I've written in SO) but please try to fix it yourself if possible, or open a new question if you can't. I'm afraid I can't debug the code in the comments section. I won't be contributing any more to this post. Cheers @CoopWesterner – rath Jul 07 '13 at 21:55
  • thanks a lot for your help. I'll try myself to fix the errors. Yup i understand it. All the best brother. I know you did huge effort on it. – Coop Westerner Jul 07 '13 at 22:09
  • allright then. In SO you thank by accepting an answer ;) @CoopWesterner – rath Jul 07 '13 at 22:10
  • One more question, i've searched it too much but didn't found until now `$sql="INSERT INTO tablename (columnnames$i) VALUES ('$_get[field_$i]')";` How do i have to insert these fields in database. Do i have to make array of inputs for this? – Coop Westerner Jul 07 '13 at 22:19
  • from which country you are from? I am from Pakistan. and thanks again. – Coop Westerner Jul 07 '13 at 22:20
  • actually i didn't read and written the code carefully that's why too much errors came. – Coop Westerner Jul 07 '13 at 22:25
  • Greece. It's nothing. Take a look at [this](http://stackoverflow.com/q/779986/2194007) – rath Jul 07 '13 at 22:25
  • Good contribution A nice Greek fella – Coop Westerner Jul 07 '13 at 22:33