I have a form where I use several variables sort of like an array, and on one of my servers (godaddy) I do not have to request the variables and it works fine. I have to change servers shortly, and I need a work around so I can request these variables
I have 12 input areas like
<input name="sd[1]" type="text" id="sd1" size='10' value='<?echo$sd[1];?>'/>
<input name="sd[2]" type="text" id="sd2" size='10' value='<?echo$sd[2];?>'/>
...
<input name="sd[12]" type="text" id="sd12" size='10' value='<?echo$sd[12];?>'/>
I need to be able to request each of the sd[#] variables, but everything I have tried does not work.
I have tried things like
for ($i=1; $i<=12; $i++){
$sd[$i]= $_POST['sd']["$i"];
}
and
for ($i=1; $i<=12; $i++){
$sd[$i]= $_POST['sd[$i]'];
}
and
$sd[1]= $_POST['sd[1]'];
I would appreciate any help that you have to offer.
Thanks,
Kelly
Use this example:
<?php
if(isset($_POST['sd'])) {
for($i = 1; $i <= count($_POST['sd']); $i++) {
echo $_POST['sd'][$i] . "<br>";
}
}
?>
<form action='' method='POST'>
<input name="sd[1]" type="text" id="sd1" size='10' value='1'/>
<input name="sd[2]" type="text" id="sd1" size='10' value='2'/>
<input name="sd[3]" type="text" id="sd1" size='10' value='3'/>
<input type=submit value='Send'>
</form>
Or you can use this code, in your html code you can set the input name like this name="sd[]"
in this case the first element is 0
see the code:
<?php
if(isset($_POST['sd'])) {
for($i = 0; $i < count($_POST['sd']); $i++) {
echo $_POST['sd'][$i] . "<br>";
}
}
?>
<form action='' method='POST'>
<input name="sd[]" type="text" id="sd1" size='10' value='1'/>
<input name="sd[]" type="text" id="sd1" size='10' value='2'/>
<input name="sd[]" type="text" id="sd1" size='10' value='3'/>
<input type=submit value='Send'>
</form>
Output:
1
2
3
Remove the double quotes around "$i".
for ($i=1; $i<=12; $i++){
$sd[$i]= $_POST['sd'][$i];
}
The grouping name name="sd[]"
already returns an array, being the number inside the []
as the index. Treat the array as you normally would.
foreach
is much suited for this task:
$sd = $_POST['sd'];
foreach($sd as $key => $value) {
// $key is integer inside name[1] or name[2], and so on
echo $key;
echo $value;
}
Actually, the loop with another assignment is superfluous, since this array already represents what you want.
$sd = $_POST['sd']; // contains the key pair values 1 => the corresponding echoed value from the form, and so on...
echo $sd[12];
First you should not use short tags for your PHP.
<? is bad, <?php is good.
The short tag option is turned off by default on most hosts.
Second you should be able to access the values like this.
$sd[1]= $_POST['sd'][1];
or even like this iff you need to loop
foreach($_POST['sd'] as $key => $value){
// $key is the number: 1-12
// $value is what is held in it. ex sd[1]
}