1

I'm trying to set up a panel that allows my admins to add posts. Not just one post, but multiple. They can click a button and it basically adds a few more input tags to add the name, link and description.

However, I'm having some issues with handling the $_POST[] values in PHP.

I'm doing something like so:

if(isset($_POST) === true){
    $pNames = $_POST["postName"];
    $pLinks = $_POST["postLink"];
    $pDescs = $_POST["postDesc"];
    foreach ($pNames as $pName) {
         foreach($epLinks as $pLink){
             foreach($pDescs as $pDesc){
                 // do stuff here
             }
         }
    }
}

My issue is that, it's basically doing it for each possible value. (Which as expected, I guess)

What would be the best way to get all of these to match up and work the way I want it?

For example, if I added two posts it'd be something like:

PostName1, PostLink1, PostDescription1

Then PostName2, PostLink2, and PostDescription2

and I'd want them all to be grouped together so I can add them into mySQL database accordingly.

1
  • 1
    You should be able to architect it so that you're able to do for ($i = 0; $i < count($_POST['posts']); $i++) { ... } and within the loop, use $i to reference each item i.e. $_POSTS['posts'][$i]['name'], $_POSTS['posts'][$i]['link'], etc. Using array notation for the form inputs will make this quite simple. Commented Feb 9, 2015 at 21:14

3 Answers 3

2

Use array notation for your form inputs:

<input type="text" name="post[0][postName]" />
<input type="text" name="post[0][postLink]" />
<input type="text" name="post[0][postDesc]" />

If you can rename the elements in this way then looping over the indexes would be the next best thing as others have described.

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

Comments

1

Working on the assumption that the size of all three arrays are always the same:

$size = count($pNames);
for($i = 0; $i < $size; ++$i){
    //do stuff here with $pNames[$i], $pLinks[$i], $pDescs[$i]
}

Comments

0

If the keys match up you can do something like this:

   foreach ($pNames as $key=>$pName) {
     $pLink = $pLinks[$key];
     $pDesc = $pDesc[$key];
     //do stuff here with $pName, $pLink, $pDesc
   }

Comments

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.