WEshruth
WEshruth

Reputation: 777

How to get value of button inside the foreach loop using post method

Objective: Get the value of buttons from $_POST method, inside foreach loop

$projects= 'Project1, Project2, Project3'//from mysql database 
$projectNames = explode(',', $projects); // to separate the project names to display one by one on button.

Displaying all the project names on buttons.

<?php foreach ($projectNames as $val):?>
<form action="projectSelected.php" method="post" id="project">
<button style="float:left" class="btn-default" value=""> <?php echo $val;?> </button>

Problem statement: When user clicks on button 'Project1', program should be able to get the value of button with $_POST['projectSelected'].

Help would be appreciated.

Upvotes: 0

Views: 3159

Answers (3)

jpclair
jpclair

Reputation: 206

1) change the name of your variables :

$Projects => $projects (PHP convention)

2) add a trim after your explode function

$projectNames = array_map('trim', $projectNames);

3) use input submit instead of buttons (similar question)

<input type="submit" style="float:left" class="btn-default" name="project" value="<?php echo $val ?>"/>

Complete example:

$projects = 'Project1, Project2, Project3'; //from mysql database 
$projectNames = explode(',', $projects); // to separate the project names to display one by one on button
$projectNames = array_map('trim', $projectNames);

Loop:

<form action="projectSelected.php" method="POST" id="project">
<?php foreach ($projectNames as $val) : ?>

    <input type="submit" style="float:left" class="btn-default" name="project" value="<?php echo $val ?>"/>
<?php endforeach ?>
</form>

Upvotes: 2

PHP Worm...
PHP Worm...

Reputation: 4224

DO this:

   <button style="float:left" name = 'projectSelected' class="btn-default"
 value=""> <?php echo $val;?> </button>

what ever you set the name of button will becomes the key of $_POST array

Upvotes: 0

Karthik Keyan
Karthik Keyan

Reputation: 426

Set the value in hidden, and then post the value

<form action="projectSelected.php" method="post" id="project"> <input type="hidden" value="<?php echo $val ?>"> <input type="submit">

Upvotes: 3

Related Questions