-2

I'm trying to upload a posted array into a database table. From within the form the user writes the text that should be uploaded into the database. What I've read and understood is that I should create the array like this:

<li> <input type='checkbox' name='R[]'  id='R[]'> <label>"+ userInput + "</label> </li>

and that every element the user creates will become R[0], R[1], R[2]..... etc...

my question is, how do I read this array within server side? How do I know how many elements are in the array from server side?

On server side I'd do an insert like this:

$sql="INSERT INTO $tbl_name (R) VALUES('$R1');";
$sql2="INSERT INTO $tbl_name (R) VALUES('$R2');";

if it wasn't an array I'd simply define R1 and R2 like this:

$R1=$_POST["R1"]; 
$R2=$_POST["R2"]; 

but I don't get how to manage the array.

Thanks!

2

1 Answer 1

3

how do I read this array within server side?

Just like you would any array.

echo $_POST['R'][0]; // get first element in that array
echo $_POST['R'][2]; // get third element in that array

How do I know how many elements are in the array from server side?

Just like you would with any array. By using count()

echo count($_POST['R']);

but how do I loop through the elements?? because I want to post all of them

Just like you would any array. Using a loop.

foreach ($_POST['R'] as $r) {
    // do something
    // echo $r;
}

FYI, you don't need array syntax for the ID attribute of your input element. But you do need to make sure it is unique.

Sign up to request clarification or add additional context in comments.

9 Comments

but how do I loop through the elements?? because I want to post all of them...
The whole point of my answer is to show you this is just an ordinary array. There's nothing really special going on here. See my updated answer for how to loop through this array.
ok I get it... so I'd simply do this foreach ($_POST['R'] as $r) { $sql3="INSERT INTO REG (ID_User, Reg) VALUES('$userid','$r');"; $tab= mysql_query($sql3, $dbh) or die ("error"); } and that way all the elements would be added to the database
Sure. You could even do it in one query if you wanted to.
I'm getting two errors: "Undefined index: R", "Invalid argument supplied for foreach()"
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.