Klapsius
Klapsius

Reputation: 3359

PHP FOR loop taking values from form (post)

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?

Upvotes: 0

Views: 81

Answers (2)

Vijayaragavendran
Vijayaragavendran

Reputation: 703

you can use

extract($_POST);

like

echo $name1a;

echo $name1b;

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

Upvotes: 3

pavel
pavel

Reputation: 27082

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
}

?>

Upvotes: 1

Related Questions