Joshua Crowley
Joshua Crowley

Reputation: 76

How to create a for each PHP loop to set variables from table data

Total beginner with PHP:

I have an form based on table data that the user can add any number of rows too, currently I'm calling the data in my .php like:

$para01 = $_POST["1_0"];
$url01 = $_POST["1_1"];
$para02 = $_POST["2_0"];
$url02 = $_POST["2_1"];

etc.

I'd like a way call the table data, so I can cater for x amount of rows

So, my pseudo code would be:

Upvotes: 0

Views: 1462

Answers (3)

Nickolas Tuttle
Nickolas Tuttle

Reputation: 208

You should use arrays! a simple way to do it would be to call all post variables, and then sort them with php...

I did it for you really quick, assuming the form input fields look like:

formstart url1 para1 url2 para2 url3 para3 and so on...

submit endform

$i=1;
$urls = array();
$paras = array();
foreach($_POST as $variable){
    if($i==1){
        array_push($urls,$variable);
        $i++;
    }else{
        array_push($paras,$variable);
        $i=1;
    }
}
echo'<table><tr><td>';
foreach($urls as $url){
    echo $url.'<br />';
}
echo'</td><td>';
foreach($paras as $para){
    echo $para.'<br />';
}
echo'</td></tr></table>';

Edit

You would pair them like this...

 $_POST = array('url1','paragraph1','url2','paragraph2','url3','paragraph3');
$urls = array();
$paras = array();
$i=1;
$c=0;
foreach($_POST as $variable){
    if($i==1){
        array_push($urls,$variable);
        $i++;
    }else{
        array_push($paras,$variable);
        $i=1;
     $c++;
    }
}

echo'<table>';
for($x=0;$x<$c;$x++){
   echo'<tr><td>'.$urls[$x].'</td><td>'.$paras[$x].'</td></tr>';
}
echo'</table>';

Upvotes: 0

Stranger
Stranger

Reputation: 10610

Ya you can use it as arrays. That is like,

<input type="text" name="para[]" />
<input type="text" name="url[]" />

<input type="text" name="para[]" />
<input type="text" name="url[]" />

<input type="text" name="para[]" />
<input type="text" name="url[]" />

And in php, you can use like

<?php
foreach($_POST[para] as $key=>$val)
{
}

foreach($_POST[url] as $key=>$val)
{
}
?>

Upvotes: 0

Hidde
Hidde

Reputation: 11911

You should make the url and the para a (two) dimensional array. Then, loop through the _POST[] variable, with a two dimensional for loop. Add the values to the array, and print them if necessary.

Upvotes: 2

Related Questions