Page 1 of 1

form values into an array

Posted: Sat Mar 12, 2005 7:51 pm
by bluesman333
i have a form, with text fields storing data in an array. each will be a row of data in the db.


<input name="value[]" type="text">
<input name="id[]" type="hidden" value="<?php print $id; ?>">


i have two questions.

how do i get these value into the db? i've been accessing each element by it's number in a while loop. ex: insert $value[1], id[1], insert $value[2]...

i'm sure this isn't the best way to do this.

also, i'm not requiring that all the fields in the form have data and am getting zero values. how do i make it so these values are never stored in the array? my idea was to only insert, into the db, the values that were not zero. is there a more efficient way?

Posted: Sat Mar 12, 2005 7:57 pm
by Chris Corbyn
To avoid storing empty values use

Code: Select all

if (!empty($var)) {
    //Do whatever
}
<input name="value[]" type="text">
This makes no sense, where's the value attribute? As far as storing data from multiple fields goes then yes you can use a loop, that's efficient enough. Everything should be in $_POST or $_GET depending upon how you send the data however, so you should be accessing it via this method.

Posted: Sat Mar 12, 2005 8:34 pm
by bluesman333
As far as storing data from multiple fields goes then yes you can use a loop, that's efficient enough.
but is there a better way? here's what i've been doing.

Code: Select all

$x = 0;
$num = count(the number of input fields in the form);
 
while ($num > $x) {
             
            INSERT INTO TABLE VALUES ($id[$x], $value[$x])
             $x++;
}

but, this will insert the values from every field in the form, even the ones with no value input.  


are you suggesting this?  

while ($num > $x) {
            if (!empty($value[$x]) {
            INSERT INTO TABLE VALUES ($id[$x], $value[$x])
             $x++;
             }
}

feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Sat Mar 12, 2005 8:46 pm
by Chris Corbyn
Yes. Although perhaps a for() loop will be more suitable? Personal preference I guess though.

Posted: Sun Mar 13, 2005 12:00 am
by John Cartwright
d11wtq wrote:Yes. Although perhaps a for() loop will be more suitable? Personal preference I guess though.
better yet, a foreach()