0

i have 5 textboxes with the name of textbox1,textbox2 ... textbox5. now what i want is that instead of putting each of their value in a variable individually I want to do it in a loop, i have my code here but after i enter submit errors like

Array to string conversion in ...

and

Undefined index: textboxArray in...

.please see what's wrong with my code.

if(isset($_POST['submit'])){
    for($i=0; $i<5; $i++){
        $sasa = $_POST["textbox".[$i].""];  
        $sql="INSERT into sasa (sasa) values('$sasa')";
        $q=$conn->query($sql);
    }   
}
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77

2 Answers2

1

The problem is this line: $sasa = $_POST["textbox".[$i].""];

You should do it as follows:

if(isset($_POST['submit'])){

    if(is_array($_POST["textbox"])){
        foreach($_POST["textbox"] as $sasa){
            //This is unsafe, use prepared statements instead
            $sql="INSERT into sasa (sasa) values('$sasa')";
            $q=$conn->query($sql);
        }
    }

}

This allows you to write your form like:

<form method="post" ... >

    <input type="text" name="textbox[]"/>
    <input type="text" name="textbox[]"/>
    <input type="text" name="textbox[]"/>

    <button type="submit">Submit</button>

</form>

In answer to your comment, this is how you could add/remove inputs dinamically using jQuery:

var control = $('<div class="controls"></div>');
control.append("<input class='form-control' type='text' name='textbox[]' placeholder='textbox'/><a href='#' class='remove_this btn btn-danger'>remove</a>");
control.appendTo('form');

control.find('.remove_this').click(function(){
    control.remove();
});
CarlosCarucce
  • 3,420
  • 1
  • 28
  • 51
1

This is incorrect:

    $sasa = $_POST["textbox".[$i].""];  
                             ^^^^

[$i] defines a new array with a single integer in it, which you then concatenate into a string. Arrays used in a string context simply become the literal word Array, which means you're effectively running this:

    $sasa = $_POST["textboxArray"];  

which doesn't exist in your form.

You want

    $sasa = $_POST["textbox{$i}"];  

instead. Note the {}.

And note that your code is vulnerable to sql injection attacks.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • do you really need braces `{}` if you are using double quotes `" .. "` ? – CodeGodie Jan 18 '16 at 17:09
  • no, but it's a good habit to get into. `$x = 7; echo "$xyz {$x}yz";` kind of thing. one's an undefined var, the other spits out `7yz` as expected. – Marc B Jan 18 '16 at 17:10
  • plus there's also php not having a greedy parser. if you try to echo out a multidimensional array in a `"`-quoted string, you get "wonky" behavior: `$x[0][1] = 'foo'; echo "$x[0][1]";` spits out `Array[1]`, because the parser stops after the first array dimension. you'd need `echo "{$x[0][1]}"` – Marc B Jan 18 '16 at 17:12