Reputation: 902
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.
Upvotes: 1
Views: 44
Reputation: 11084
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
}
Upvotes: 0
Reputation: 451
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]
}
Upvotes: 1
Reputation: 60413
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.
Upvotes: 2