0

I have form with elements (text fields), 5 diference elements names:

name1a   name1b
name2a   name2b
name3a   name3b
name4a   name4b
name5a   name5b

and php file:
for ($i = 1; $i <= 5; $i++) {
    echo $i,"<br/>";
 $name. $i .'a' = $_POST['name'.$i.'a'];
 echo $name. $i .a;
}

It is posible read text fields with for loop or no? And pass values to sql query aswell?

3
  • you could loop for $_POST...? Commented Jun 30, 2014 at 8:02
  • yes $_POST is an array Commented Jun 30, 2014 at 8:02
  • 1
    @Sudhir yes loop for POST Commented Jun 30, 2014 at 8:03

2 Answers 2

3

you can use

extract($_POST);

like

echo $name1a;

echo $name1b;

you can access the value with the text-box names itself

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

Comments

1

It´s possible, but it´s a bad practice and I can´t recommend it you.

So, use arrays to store similar values from form (when you indexed your names, every times use arrays instead).

<input name="name[1]" ...> <!-- key isn't neccesary here, name[] will count from 0 -->
<input name="name[2]" ...>
<input name="name[3]" ...>

<?php

for ($i = 1; $i <= count($_POST['name']), $i++) {
    echo $_POST['name'][$i] . '<br>'; // work directly with this variables/array, don't create duplicate vars
}

?>

9 Comments

why u can't recomend?
So bether is 5 times take values from form and make 5 sql querys aswell?
Why you need to create X new variables when you have the same values in same-named keys in array? Why you now speak about more SQL queries when in your question is no SQL query? Of course, use just one SQL query instead of five, it's okay and I've never said anything else. You can use POST array in your SQL query, you don't need collection of new variables.
I don't know what query you have, for example: insert into table (name, lastname, phone) VALUES ('$_POST['name'][0]', '$_POST['name'][1]', '$_POST['name'][2]'); - there are bad key names, no SQL injection prevention, but as example it can be.
so 5 times: sqlsrv_query( $conn, $sql1); sqlsrv_query( $conn, $sql2); sqlsrv_query( $conn, $sql3);.... and 5 times insert into ... is bether then this with FOR Loop?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.