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

Evana
  • 353
  • 1
  • 4
  • 18

1 Answers1

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.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • but how do I loop through the elements?? because I want to post all of them... – Evana May 14 '14 at 01:04
  • 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. – John Conde May 14 '14 at 01:06
  • 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 – Evana May 14 '14 at 01:11
  • Sure. You could even do it in one query if you wanted to. – John Conde May 14 '14 at 01:11
  • I'm getting two errors: "Undefined index: R", "Invalid argument supplied for foreach()" – Evana May 14 '14 at 01:21
  • Do a `var_dump($_POST);` and post the results here – John Conde May 14 '14 at 01:22
  • That explains your error although I would expect it to be an empty array instead of null. Is your form set to POST? What does `var_dump($_REQUEST);` show? – John Conde May 14 '14 at 01:34
  • it returns nothing :( – Evana May 14 '14 at 01:39
  • There's a disconnect between your form and your PHP code. Unfortunately I can't diagnose it from here. If there is any code or rewriting going on between your form and code it may be the culprit. – John Conde May 14 '14 at 01:42