Getting buttons and textboxes within loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Getting buttons and textboxes within loop

Post by Goofan »

Didnt know how ever to explain the title better hope it helps alittle atleast :D
I got this code and well i need to get out the names of every submit button and every textbox name so i can say if button(1) pressed then take info from textbox (1) and put into database. I have no idé on how to make this :?: , please help...

If u submit any code please coment around it so i understand (im learning php)

Thanks in advance to everyone =)

Code: Select all

 
 
 <table border="1">
   <tr>
    <th>Units</th>
        <th>AtkArm</th>
    <th>Buyfor</th>
        <th>Sellfor</th>
    <th>You Own</th>
        <th>Buy</th>
   </tr>
 <?php while ($row1 = mysql_fetch_assoc($result1)): ?>
 <tr>
        <th><?php echo $row1['Units'] ;?></th>
    <th><?php echo $row1['AtkHp'] ;?></th>
        <th><?php echo $row1['Buyfor'] ;?></th>
    <th><?php echo $row1['Sellfor'] ;?></th>
        <th><?php echo $my['swordmen'] ?></th> <--- this needs to be 3 diffrent datatables (swordmen, macemen, pikemen---|
    <th>
        <font color="black" valign= "top"><input style='width:45;height:20' type="text" name="input ITD1" size="250" class="textbox" value=""></font>
        <input style='width:45;height:30;font-weight:bold' name="submit" type="submit" class="submit" value="Buy!">
    </th>
   </tr>
 <?php endwhile; ?>
 </table>
 
Last edited by Goofan on Tue Nov 17, 2009 2:23 am, edited 1 time in total.
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Getting buttons and textboxes within loop

Post by iankent »

If your HTML submit button has a name, as yours does ('submit'), the value of it is passed to PHP as part of the POST/GET variables. So, take this example HTML form:

Code: Select all

 
<form action="somewhere.php" method="post">
<input type="text" name="text1" value="Something here" />
<input type="text" name="text2" value="Something else" />
<input type="submit" name="submit" value="Submit Text1" />
<input type="submit" name="submit" value="Submit Text2" />
</form>
 
If the user clicks 'Submit Text1', then in PHP you'll find that $_POST['submit'] == 'Submit Text1', and therefore you know the user wanted to submit $_POST['text1']. You could use something like this in PHP:

Code: Select all

 
$submit = isset($_POST['submit']) ? $_POST['submit'] : '';
switch($submit) {
    case 'Submit Text1':
        $value = isset($_POST['text2']) ? $_POST['text1'] : '';
    break;
    case 'Submit Text2':
        $value = isset($_POST['text2']) ? $_POST['text2'] : '';
    break;
    default:
        $value = "";
    break;
}
echo $value;
 
Depending on the value of $_POST['submit'] it reads $value from a different $_POST variable

hope that makes sense and hope I understood correctly :)
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Re: Getting buttons and textboxes within loop

Post by Goofan »

well if i understood correct u only explained how to get it from "without a loop" correct? but within a loop u can only see one "code wise" and then u can see 3 in the oppend (on the webb) "design wise" how do u determine which is which of the buttons? is it automatically called submit text1 then text2 s.o?
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Getting buttons and textboxes within loop

Post by iankent »

You've lost me :P

When you output the form you'd need to give each submit button a separate value. Only the value of whichever one is clicked will be sent back. So if you have a loop like this:

Code: Select all

 
for($i = 1; $i <= 10; $i++) {
    ?>
    <input type="submit" name="submit" value="Submit button <?=$i?>" />
    <?
}
 
Then you'd end up with 10 submit buttons, all called 'submit', with different values. If the user clicks the button with the value 'Submit button 4', then the value of $_POST['submit'] will equal 'Submit button 4' when the form is submitted.

Put simply, you choose the names and values of the buttons you output in HTML, and your PHP code needs to check for those values when the form is submitted to decide which of your buttons was pressed to take the appropriate action.

All of the <input type="text"> values will be returned regardless of which submit button is pressed, so the only way to decide which text box the user wanted to submit is based on the value of the submit button.

I'm not sure why it being inside/outside a loop is relevant, the principle is the same - every submit button needs a unique value, and your script needs to check which value it gets back to decide what to do with the data submitted.
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Re: Getting buttons and textboxes within loop

Post by Goofan »

<?=$i?>

so this is what i need?


well ok so every "button" got a unique value and u can get it like u said <?=$i?>... but how do u assine so that if "button4" is pressed then transfer value in textbox4 to database. i "sort of" understood ure code but if ure code got all i want please comment it abit more as im "not" that good at php im only on basic/advanced stage =) altho thanks for every little help i get :D
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Getting buttons and textboxes within loop

Post by iankent »

Goofan wrote:<?=$i?>

so this is what i need?


well ok so every "button" got a unique value and u can get it like u said <?=$i?>... but how do u assine so that if "button4" is pressed then transfer value in textbox4 to database. i "sort of" understood ure code but if ure code got all i want please comment it abit more as im "not" that good at php im only on basic/advanced stage =) altho thanks for every little help i get :D
*vbg* what's a basic/advanced stage? :)

Here's a more complete (and commented) example:

Code: Select all

 
<? // output a basic form ?>
<form action="submit.php" method="post">
<?
   // use a loop to output three unique textboxes:
  for($i = 1; $i <= 3; $i++) {
    ?>
    <input type="text" name="text<?=$i?>" value="This is text box <?=$i?>" />
    <?
  }
?>
<?
   // use a loop to output three unique submit buttons:
  for($i = 1; $i <= 3; $i++) {
    ?>
    <input type="submit" name="submit" value="submit<?=$i?>" />
    <?
  }
?>
</form>
 
The for{} loop simply outputs three submit buttons - using $i as the counter so each button has a unique value (i.e., submit1, submit2, submit3). The values are kind of irrelevant, as long as they're unique.

Next bit is the code for submit.php. You need to detect which button was pressed and update the db with the correct value, e.g.

Code: Select all

 
<?
    $submit_value = $_POST['submit']; // get the value of the button that was clicked
    switch($submit_value) { // check against predefined values
        case 'submit1':
            // submit button 1 was pressed, so lets get text1's value:
            $value = $_POST['text1'];
            $column = 'firstname'; // for this example, 'text1' was the users first name, so we want to update the firstname column in the db
        break;
        case 'submit2':
            // submit button 2 was pressed, so lets get text1's value:
            $value = $_POST['text2'];
            $column = 'lastname'; // 'text2' was the users last name, so we want to update the lastname column
        break;
        case 'submit3':
            // submit button 1 was pressed, so lets get text1's value:
            $value = $_POST['text3'];
            $column = 'location'; // 'text3' was the users location, so we want to update the location column
        break;
    }
?>
 
So, that bit of code detects the value of 'submit', and depending which one was clicked, retrieves a different value from $_POST and assigns the corresponding column name to $column.

You could then use code like this to update the db:

Code: Select all

 
// escape $value before writing to db
$value = mysql_real_escape_string($value);
// build the query using $value and $column from above
$q = "update tablename set $column='$value' where userid=1;";
mysql_query($q); // execute the query
if(!mysql_error()) { // check for an error
    echo "Update was successful";
} else {
    echo "Update failed: ".mysql_error();
}
 
Hopefully that explains it a bit better - depending on which button is clicked, the php code updates a different column with the correct value.
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Re: Getting buttons and textboxes within loop

Post by Goofan »

thanks a bunch mate =) i guess im more basic then advanced php developer =) learning as i speak.. :D
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Getting buttons and textboxes within loop

Post by iankent »

No problem :) we're all still learning!! Actually, the more I learn the less I think I know lol...
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Re: Getting buttons and textboxes within loop

Post by Goofan »

iankent wrote:No problem :) we're all still learning!! Actually, the more I learn the less I think I know lol...
haha i like ure comment =) and it is so true thanks again =)
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Re: Getting buttons and textboxes within loop

Post by Goofan »

ok so i dont get it to work when i inplant my code and ures... can u help?
my code on the site where i need it... all of the page...

Code: Select all

 
 
<?php
    // Get the database connector stuff
    include "../login/database.php";
     
    // Build our query
    $sql1 = 'SELECT * FROM `infantries`';
     
    // Get the result if there is one
   // DO NOT die() IN PRODUCTION!!!
   if (!$result1 = mysql_query($sql1)) 
    {
     die('The query<br /><strong>' . $sql1 . '</strong><br />failed:<br />' . mysql_error());
    }
?>
 

Code: Select all

 
<?php
 
 
  $id =(isset($_GET['saved_id'])) ? (int)$_GET['saved_id'] : false;
    if($id !== false) {
    $sql="SELECT * FROM konto WHERE saved_id=$id";      //selecting all from DB "Konto" where saved_id is the same as in the array $id
 } 
    else 
 {
    echo "NO saved_id!";
 }
     
 
$result = mysql_query($sql) or die(mysql_error());//Välj all info i tall. //hämtar all info från tabell
 
                 
while($row = mysql_fetch_array( $result )) //hämtar info från tabell.
{
    $my['Swordmen'] = $row['swordmen'];
    $my['Macemen'] = $row['macemen'];
    $my['Pikemen'] = $row['pikemen'];
}
if ($_POST["submit"])//Kollar om knappen SUBMIT använts.
{
if (($_POST[text1]=="") || ($_POST[text2]=="") || ($_POST[text3]=="")
{
header('Refresh: 0; url=logga_in2.php');//Skickas till angiven sida efter en viss tid.
exit;
}
$sql="UPDATE konto SET swordmen='".$_POST[text1]."' WHERE $id=saved_id";//Sätt upp SQL fråga.
$result = mysql_query($sql) or die(mysql_error());//Välj all info i tabell.
$sql="UPDATE konto SET macemen='".$_POST[text2]."' WHERE $id=saved_id";//Sätt upp SQL fråga.
$result = mysql_query($sql) or die(mysql_error());//Välj all info i tabell.
$sql="UPDATE konto SET pikemen='".$_POST[text3]."' WHERE $id=saved_id";//Sätt upp SQL fråga.
$result = mysql_query($sql) or die(mysql_error());//Välj all info i tabell.
}
?>
 

Code: Select all

 
<? // output a basic form ?>
<form action="submit.php" method="post">
<?
    // use a loop to output three unique textboxes:
  for($i = 1; $i <= 3; $i++) {
?>
<input type="text" name="text<?=$i?>" value="This is text box <?=$i?>" />
<?
}
?>
<?
// use a loop to output three unique submit buttons:
for($i = 1; $i <= 3; $i++) {
?>
<input type="submit" name="submit" value="submit<?=$i?>" />
<?
}
?>
 
</form>
 

Code: Select all

 
<html>
<head>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<title>Infantrie</title>
</head>
<body bgcolor="#A4A8B0">
    <style type="text/css">     <!--selecting the style type-->
        <!--
        a:link {text-decoration: none; color: black}
        a:visited {text-decoration: none; color: black}
        a:active {text-decoration: none; color: black} 
        a:visited {text-decoration: none; color: black}
        .textbox { background-color: #DEB887; }
        .submit { background-color: #DEB887; }
        -->
    </style>        <!--ending the style type-->
 
    
    <p>                     
        Är du villig att köpa soldater? Tror du att du är man nog att göra det?
    </p>
 <table border="1">
   <tr>
    <th>Units</th>
        <th>AtkArm</th>
    <th>Buyfor</th>
        <th>Sellfor</th>
    <th>You Own</th>
        <th>Buy</th>
   </tr>
 <?php while ($row1 = mysql_fetch_assoc($result1)): ?>
 <tr>
        <th><?php echo $row1['Units'] ;?></th>
    <th><?php echo $row1['AtkHp'] ;?></th>
        <th><?php echo $row1['Buyfor'] ;?></th>
    <th><?php echo $row1['Sellfor'] ;?></th>
        <th><?php echo $my[$row1['Units']]; ?></th>
    <th>
        <font color="black" valign= "top"><input style='width:45;height:20' type="text" name="input ITD1" size="250" class="textbox" value=""></font>
        <input style='width:45;height:30;font-weight:bold' name="submit" type="submit" class="submit" value="Buy!">
    </th>
   </tr>
 <?php endwhile; ?>
 </table>
</html>
 
END OF PAGE
*******-----------------------------------------*******
PAGE: Submit.php

Code: Select all

 
<?
    $submit_value = $_POST['submit']; // get the value of the button that was clicked
    switch($submit_value) { // check against predefined values
         case 'submit1':
             // submit button 1 was pressed, so lets get text1's value:
            $value = $_POST['text1'];
             $column = 'swordmen'; // for this example, 'text1' was the users first name, so we want to update the firstname column in the db
         break;
         case 'submit2':
             // submit button 2 was pressed, so lets get text1's value:
             $value = $_POST['text2'];
             $column = 'macemen'; // 'text2' was the users last name, so we want to update the lastname column
         break;
         case 'submit3':
             // submit button 1 was pressed, so lets get text1's value:
             $value = $_POST['text3'];
             $column = 'pikemen'; // 'text3' was the users location, so we want to update the location column
         break;
     }
?>
 
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Getting buttons and textboxes within loop

Post by iankent »

Perhaps I didn't make it clear, but you weren't supposed to simply copy and paste my code into yours, that definately wont work. You need to apply the theory behind my code to your code.

Apologies if I now sound rather stupid, but I can't work out from your code what exactly you're trying to do... perhaps you could explain step-by-step what you want to achieve?
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Re: Getting buttons and textboxes within loop

Post by Goofan »

allright from start =)
here i start a loop and making the output that is shown in the attachment...

Code: Select all

 
 <table border="1">
   <tr>
    <th>Units</th>
        <th>AtkArm</th>
    <th>Buyfor</th>
        <th>Sellfor</th>
    <th>You Own</th>
        <th>Buy</th>
   </tr>
 <?php while ($row1 = mysql_fetch_assoc($result1)): ?>
 <tr>
        <th><?php echo $row1['Units'] ;?></th>
    <th><?php echo $row1['AtkHp'] ;?></th>
        <th><?php echo $row1['Buyfor'] ;?></th>
    <th><?php echo $row1['Sellfor'] ;?></th>
        <th><?php echo $my[$row1['Units']]; ?></th>
    <th>
        <font color="black" valign= "top"><input style='width:45;height:20' type="text" name="input ITD1" size="250" class="textbox" value=""></font>
        <input style='width:45;height:30;font-weight:bold' name="submit" type="submit" class="submit" value="Buy!">
    </th>
   </tr>
 <?php endwhile; ?>
 </table>
 
as u proberbly can see i got a while with the buttons and the textboxes. The while is looping out 3 buttons and 3 textboxes. Now what i need to do is: what i type into textbox will be uppdated into the datatable "swordmen" as it is currently as i press the button.
However when u do the same on the second textbox and button u will uppdate it to the datatable "macemen"... Next to datatable "pikemen". so i need to get the name of the buttons and textboxes so i can modifie them as i need =) hope it explaines else ask what specificly u dont understand
Attachments
here i got the 3 submit buttons and the 3 textboxes...
here i got the 3 submit buttons and the 3 textboxes...
Problem.jpg (16.88 KiB) Viewed 378 times
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Re: Getting buttons and textboxes within loop

Post by Goofan »

my current page =)
without any adjustments

Code: Select all

 
    <?php
    // Get the database connector stuff
    include "../login/database.php";
     
    // Build our query
    $sql1 = 'SELECT * FROM `infantries`';
     
    // Get the result if there is one
   // DO NOT die() IN PRODUCTION!!!
   if (!$result1 = mysql_query($sql1)) 
    {
     die('The query<br /><strong>' . $sql1 . '</strong><br />failed:<br />' . mysql_error());
    }
 ?>
 

Code: Select all

 
<?php
 
 
  $id =(isset($_GET['saved_id'])) ? (int)$_GET['saved_id'] : false;
    if($id !== false) {
    $sql="SELECT * FROM konto WHERE saved_id=$id";      //selecting all from DB "Konto" where saved_id is the same as in the array $id
 } 
    else 
 {
    echo "NO saved_id!";
 }
     
 
$result = mysql_query($sql) or die(mysql_error());//Välj all info i tall. //hämtar all info från tabell
 
                 
while($row = mysql_fetch_array( $result )) //hämtar info från tabell.
{
    $my['Swordmen'] = $row['swordmen'];
    $my['Macemen'] = $row['macemen'];
    $my['Pikemen'] = $row['pikemen'];
}
?>
<html>
<head>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<title>Infantrie</title>
</head>
<body bgcolor="#A4A8B0">
    <style type="text/css">     <!--selecting the style type-->
        <!--
        a:link {text-decoration: none; color: black}
        a:visited {text-decoration: none; color: black}
        a:active {text-decoration: none; color: black} 
        a:visited {text-decoration: none; color: black}
        .textbox { background-color: #DEB887; }
        .submit { background-color: #DEB887; }
        -->
    </style>        <!--ending the style type-->
 
    
    <p>                     
        Är du villig att köpa soldater? Tror du att du är man nog att göra det?
    </p>
 <table border="1">
   <tr>
    <th>Units</th>
        <th>AtkArm</th>
    <th>Buyfor</th>
        <th>Sellfor</th>
    <th>You Own</th>
        <th>Buy</th>
   </tr>
 <?php while ($row1 = mysql_fetch_assoc($result1)): ?>
 <tr>
        <th><?php echo $row1['Units'] ;?></th>
    <th><?php echo $row1['AtkHp'] ;?></th>
        <th><?php echo $row1['Buyfor'] ;?></th>
    <th><?php echo $row1['Sellfor'] ;?></th>
        <th><?php echo $my[$row1['Units']]; ?></th>
    <th>
        <font color="black" valign= "top"><input style='width:45;height:20' type="text" name="input ITD1" size="250" class="textbox" value=""></font>
        <input style='width:45;height:30;font-weight:bold' name="submit" type="submit" class="submit" value="Buy!">
    </th>
   </tr>
 <?php endwhile; ?>
 </table>
</html>
 
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Getting buttons and textboxes within loop

Post by iankent »

Ok, I think I've got it :)

One question though, if you *always* have Pikemen, Swordmen and Macemen, is there any reason for using a while loop rather than just outputting statically?

Anyways, you could do it by changing the NAME of the submit buttons to Pikemen, Swordmen and Macemen, e.g.

Code: Select all

<input style='width:45;height:30;font-weight:bold' name="<?=$row1['Units']?>" type="submit" class="submit" value="Buy!">
You'll also need to give each of the textboxes a unique name, e.g.

Code: Select all

<input style='width:45;height:20' type="text" name="qty_<?=$row1['Units']?>" size="250" class="textbox" value="">
That'll give you three text boxes - qty_Pikemen, qty_Swordmen and qty_Macemen.

Then, when the form is submitted, you can check to see which was pressed like this:

Code: Select all

if(isset($_POST['Pikeman'])) {
    // the Pikeman Buy button was clicked - so you need to use qty_Pikemen
    $unit = "Pikeman";
    $qty = $_POST['qty_Pikemen';
}
if(isset($_POST['Swordmen'])) {
    // the Swordmen Buy button was clicked
    $unit = "Swordmen";
    $qty = $_POST['qty_Swordmen'];
}
if(isset($_POST['Macemen'])) {
    // the Macemen Buy button was clicked
    $unit = "Macemen";
    $qty = $_POST['qty_Macemen'];
}
after that bit of code you now have two variables ($unit and $qty) that tell you which buy button was clicked, and what value was entered in the corresponding text box

Next thing you'll want to do is check that they have both been filled - if not, the form wasn't submitted correctly e.g.

Code: Select all

if(!isset($unit) || !isset($qty)) {
echo 'Go away and stop trying to break my code...';
exit();
}
After all that you can do what you like with the values, e.g. increase the quantity in your database table etc.

Hope that makes sense :)
User avatar
Goofan
Forum Contributor
Posts: 305
Joined: Wed Nov 04, 2009 2:11 pm
Location: Sweden

Re: Getting buttons and textboxes within loop

Post by Goofan »

I´ll try it
and no i might change the "swordmen e.t.c." to diffrent later on :D
Post Reply