Jump to content


Photo

An HTML form with PHP Question


  • Please log in to reply
14 replies to this topic

#1 danthethug

danthethug
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 14 May 2006 - 11:46 AM

Hello, Ive been coding with PHP for quite some time now (2-3 years) and have gotten fairly far from my eyes. Anyhow, Ive never come across the use of this code snippet below of HTML:
      <td align="center" bgcolor="#0E0E17"><input type="checkbox" name="remove[]" value="<? print "$wep[ID]"; ?>"></td>
Please ignore the php in that but the main question is, The name. Why does it have the [] after remove. This form is for multiple Checkboxes that will be used with just a few lines of PHP code to delete the Table Row of information dealing with $wep[ID]. I cant figure out how the [] is helping but i notice other forms that do the same thing this is doing using that, So just wondering how i might be able to use this feature also? [img src=\"style_emoticons/[#EMO_DIR#]/unsure.gif\" style=\"vertical-align:middle\" emoid=\":unsure:\" border=\"0\" alt=\"unsure.gif\" /]

Thanks, Daniel.

#2 redbullmarky

redbullmarky
  • Staff Alumni
  • Advanced Member
  • 2,863 posts
  • LocationBedfordshire, England

Posted 14 May 2006 - 11:49 AM

if you have a group of checkboxes, then using the [] is a way to keep all of the posted results in the same place, ie an array. so in php after submitting the form, you will have a $_POST or $_GET array containing the values of the checkbox:

$checkboxarray = $_POST['remove'];

hope that helps.
"you have to keep pissing in the wind to learn how to keep your shoes dry..."

I say old chap, that is rather amusing!

#3 danthethug

danthethug
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 14 May 2006 - 11:53 AM

Hmm, Well i put it as just $remove on the SQL query and it returned Array as the Value. Im gonna try to force it into a POST and see if that works lol. Below is the entire page:

<?

include "header.php";

$Check = @mysql_num_rows(mysql_query("select * from User_Hitlist where User_ID='$stat[ID]'"));

?>

<center>
    <table border="0.5" style="border-collapse: collapse" width="100%"  bordercolor="#999999">
    <tr>
<?

if ($submit) {

$check2 = @mysql_num_rows(mysql_query("select * from Users where Username='$hit'"));
if ($check2 > 0) {
?>
<td width="100%">Player added to hitlist!<DIV ID="dek"></DIV>
<?
mysql_query("INSERT INTO `User_Hitlist` ( `Username` , `User_ID` ) VALUES ('$hit', '$stat[Id]')");
} else {
print "Sorry, No user found with $hit as username!";
}
}

?>

<?

if ($subrem) {

$check2 = @mysql_num_rows(mysql_query("select * from User_Hitlist where ID='$remove'"));
if ($check2 > 0) {

 ?> <td width="100%">Player removed from hitlist!<DIV ID="dek"></DIV><?
mysql_query("DELETE FROM `User_Hitlist` WHERE Username='$remove' AND User_ID='$stat[Id]'");
} else {
print "Sorry, No user found with $remove as username!";
}
}

?>

<br>
<div align="center">
  <center>

  <table border="1" cellpadding="2" cellspacing="0" style="border-collapse: collapse" id="AutoNumber1" bgcolor="#0E0E17" bordercolor="#FFFFFF">
    <tr>
      <td colspan="6">
          <p align="center"><b>Hit List</b><br>
                    (<? print "$Check"; ?> / <? print "$stat[MaxHitlist]"; ?>)
      </td>
    </tr>
    <tr>
      <td width="100%" colspan="6">

      <table border="0" cellpadding="10" cellspacing="0" style="border-collapse: collapse" width="100%" id="AutoNumber2">
        <tr>
          <td width="100%">
                      <form method="post">
          <p align="center">Username: <input type="text" size="20" name="hit">
          <input type="submit" value="Add to Hit List" name="submit"></p>
        </form>

              
          </td>
        </tr>
      </table>
      </td>
    </tr>
 <form method="post">
    <tr>
      <td width="150"><b>Name</b></td>
      <td width="150" align="center"><b>Power</b></td>
      <td width="150"><b>Hits</b></td>
      <td width="150" align="center"><b>Remove</b></td>
    </tr>

<?

    $wsel=mysql_query("select * from User_Hitlist where User_ID='$stat[Id]' order by ID+0 DESC ");
    while ($wep = @mysql_fetch_array($wsel)) {

$player = @mysql_fetch_array(mysql_query("select * from Users where Username='$wep[Username]'"));

?>

          <tr>
      <td bgcolor="#0E0E17"><a href="profile.php?id=<? print "$player[Id]"; ?>"><? print "$wep[Username]"; ?></a></td>
      <td align="center"  bgcolor="#0E0E17"><font color="#00FFff"><? $Power = to_money($player[Power]); print "$Power"; ?></font></td>
      <td bgcolor="#0E0E17"><? $Hits = to_money($wep[Hits]); print "$Hits"; ?></td>
      <td align="center" bgcolor="#0E0E17"><input type="checkbox" name="remove[]" value="<? print "$wep[ID]"; ?>"></td>
    </tr>

<?
}
?>
              <tr>
          <td colspan="3"></td>
          <td align="center">
              <input type="submit" name="subrem" value="Remove">
          </td>
      </tr>
 </form>

  </table>
  <br>
  </center>
</div>



            </td>
          </tr>
        
        
        </tr>
</table>

</td>
</table>
</table>
</center>

If that will help im not sure but most likely lol.

QUICK EDIT:

This is what i get when i change it around to the Variable name and value you suggested in your post. It gives the same error even if i had put just $remove.
Sorry, No user found with Array as username!


#4 redbullmarky

redbullmarky
  • Staff Alumni
  • Advanced Member
  • 2,863 posts
  • LocationBedfordshire, England

Posted 14 May 2006 - 12:04 PM

that's because you have to treat an array as such.

$test = array('a', 'b', 'c');

echo $test; // output is 'Array'

echo $test[1]; // output is 'b'

print_r($test); // output is the full array

so you need to go through each of your array elements and process them, for example:

$sql = "delete from users where ";
$checkboxarray = $_POST['remove'];

foreach ($checkboxarray as $value)
{
   $sql.= "username = '$value' OR ";
}


that should give you an idea
cheers
Mark
"you have to keep pissing in the wind to learn how to keep your shoes dry..."

I say old chap, that is rather amusing!

#5 danthethug

danthethug
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 14 May 2006 - 12:09 PM

[!--quoteo(post=373712:date=May 14 2006, 08:04 AM:name=redbullmarky)--][div class=\'quotetop\']QUOTE(redbullmarky @ May 14 2006, 08:04 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
that's because you have to treat an array as such.

$test = array('a', 'b', 'c');

echo $test; // output is 'Array'

echo $test[1]; // output is 'b'

print_r($test); // output is the full array

so you need to go through each of your array elements and process them, for example:

$sql = "delete from users where ";
$checkboxarray = $_POST['remove'];

foreach ($checkboxarray as $value)
{
   $sql.= "username = '$value' OR ";
}


that should give you an idea
cheers
Mark
[/quote]

Well, now im kind of lost, You say i need to process each Array element. Well what im using this for is a MMORPG, and there could be 100 users, Does this mean id have to have 100 lines of this code? I also dont understand the $value part. Where is it pulling this from?

QUICK EDIT:

Is it pulling the $value variable from the HTML value="<? print "$wep[ID]"; ?>"?

#6 redbullmarky

redbullmarky
  • Staff Alumni
  • Advanced Member
  • 2,863 posts
  • LocationBedfordshire, England

Posted 14 May 2006 - 12:50 PM

[!--quoteo(post=373713:date=May 14 2006, 01:09 PM:name=Php Man)--][div class=\'quotetop\']QUOTE(Php Man @ May 14 2006, 01:09 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
Well, now im kind of lost, You say i need to process each Array element. Well what im using this for is a MMORPG, and there could be 100 users, Does this mean id have to have 100 lines of this code? I also dont understand the $value part. Where is it pulling this from?

QUICK EDIT:

Is it pulling the $value variable from the HTML value="<? print "$wep[ID]"; ?>"?
[/quote]

well put it this way. if you didnt have the [], you'd have to give each checkbox a different name, which would mean you'd have to process an unknown quantity of various variable names - eg $_POST['remove1'], $_POST['remove2'], etc, etc. not very dynamic.

however - giving it the brackets [], you can give a group of checkboxes a single name and process them much easier.

in my example, 'foreach' goes through each element of an array (automatic loop) and puts the value in $value, for easy reference. what my example does is builds up the query bit by bit - so you'll end up with something like: "DELETE FROM USERS WHERE username = 'thisuser' OR username = 'thatuser' etc etc".

if you understand how arrays work, then all you need to know is that using the [] brackets forces a group of values into an array. in your case, you have an array called $_POST['remove'] where each element contains the VALUE of the checkbox that was checked.

"you have to keep pissing in the wind to learn how to keep your shoes dry..."

I say old chap, that is rather amusing!

#7 danthethug

danthethug
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 14 May 2006 - 01:02 PM

[!--quoteo(post=373720:date=May 14 2006, 08:50 AM:name=redbullmarky)--][div class=\'quotetop\']QUOTE(redbullmarky @ May 14 2006, 08:50 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
well put it this way. if you didnt have the [], you'd have to give each checkbox a different name, which would mean you'd have to process an unknown quantity of various variable names - eg $_POST['remove1'], $_POST['remove2'], etc, etc. not very dynamic.

however - giving it the brackets [], you can give a group of checkboxes a single name and process them much easier.

in my example, 'foreach' goes through each element of an array (automatic loop) and puts the value in $value, for easy reference. what my example does is builds up the query bit by bit - so you'll end up with something like: "DELETE FROM USERS WHERE username = 'thisuser' OR username = 'thatuser' etc etc".

if you understand how arrays work, then all you need to know is that using the [] brackets forces a group of values into an array. in your case, you have an array called $_POST['remove'] where each element contains the VALUE of the checkbox that was checked.
[/quote]

Oh, I have horrible knowledge of arrays, but thats about it. Rofl, So all i use is the Example you provided me Above and just tweak it to fit my needs and that should work?


#8 redbullmarky

redbullmarky
  • Staff Alumni
  • Advanced Member
  • 2,863 posts
  • LocationBedfordshire, England

Posted 14 May 2006 - 01:26 PM

[!--quoteo(post=373723:date=May 14 2006, 02:02 PM:name=Php Man)--][div class=\'quotetop\']QUOTE(Php Man @ May 14 2006, 02:02 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
Oh, I have horrible knowledge of arrays, but thats about it. Rofl, So all i use is the Example you provided me Above and just tweak it to fit my needs and that should work?
[/quote]

the principles i showed you should set you on your way. all you've got to remember is that array is nothing more than a group of variables grouped together with a common name.

look at [a href=\"http://www.php.net/foreach\" target=\"_blank\"]http://www.php.net/foreach[/a] to get an idea of not just the 'foreach' command, but arrays in general. for something like what you appear to be doing, arrays of some form are going to be essential.
"you have to keep pissing in the wind to learn how to keep your shoes dry..."

I say old chap, that is rather amusing!

#9 danthethug

danthethug
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 14 May 2006 - 01:37 PM

[!--quoteo(post=373727:date=May 14 2006, 09:26 AM:name=redbullmarky)--][div class=\'quotetop\']QUOTE(redbullmarky @ May 14 2006, 09:26 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
the principles i showed you should set you on your way. all you've got to remember is that array is nothing more than a group of variables grouped together with a common name.

look at [a href=\"http://www.php.net/foreach\" target=\"_blank\"]http://www.php.net/foreach[/a] to get an idea of not just the 'foreach' command, but arrays in general. for something like what you appear to be doing, arrays of some form are going to be essential.
[/quote]

Ok, Will do and thanks for your help :-P

#10 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 14 May 2006 - 02:19 PM

when you have a form that the user can enter in multiple values (such as a list of checkboxes) it is not very convenient to name each checkbox a seperate name and process each one individually. So, what you would do is use the brackets []

<input type="checkbox" name="remove[]" value="<? print "$wep[ID]"; ?>">

this will create an array called remove that will hold the value of each checkbox that is selected. An Array is nothing more than a bunch of variable grouped together under one name, for the sake of convenience.

you would access each one individually by specifying the key. the key is simply the number that points to a value in your array. example:

you have a form with a checkbox list that asks the user to check off all of their favorite colors:

Check off all your favorite colors:
<form action = 'listcolors.php' method = 'post'>
   <input type = 'checkbox' name = 'colors[]' value='Red'>Red<br>
   <input type = 'checkbox' name = 'colors[]' value='Orange'>Orange<br>
   <input type = 'checkbox' name = 'colors[]' value='Green'>Green<br>
   <input type = 'checkbox' name = 'colors[]' value='Blue'>Blue<br>
   <input type = 'checkbox' name = 'colors[]' value='Violet'>Violet<br>
   <input type = 'submit' value='submit'>
</form>

the user can check whichever colors (s)he likes and click the submit button. Clicking the submit button will send the array colors (remember, an array is nothing more than a bunch of variables grouped under the same name).

Now, in listcolors.php you will initially access your array with $_POST['colors']

$_POST is an array in and of itself. it holds all of the information sent from the form via the post method. so if you had a few radio buttons thrown and some text fields with their own names thrown onto that form, you would access them all through $_POST example:

echo $_POST['textfieldname'];
echo $_POST['radiobuttonname'];
echo $_POST['colors'];

Now lets get back to your colors array. As shown above, if you were to echo $_POST['colors'] all that would print was "Array" instead of the colors. You have to specify which (or all) color(s) you wish to display. But before we look at how to access each color selected, I want to do this:

$colors = $_POST['colors'];

all i am doing is making a new array that holds the same information as the $_POST array. seems pointless and superfluous, right? well, it is certainly not necessary. But I like to do this because it reduces the amount of quote you have to use. Quotes tend to get very confusing at times, and many syntax errors are direct results of improperly used quotes. So the less quotes, the better, in my opinion.

Please note that $colors is not the same as your original colors[] array until i actually set it to be the same, as i just did above. I could have just as easily done this:

$favoritecolors = $_POST['colors'];

so anyways, now that we have made this new array $colors, lets print out the colors the user selected. Remember earlier when I said that each value had a key that pointed to it? well the key is nothing more than a number, starting with a zero. each color will have its own key

$color[0]
$color[1]
$color[2]
$color[3]
$color[4]

now, there were only 5 color choices in the form, so the highest key we can possibly have is 4 (remember, it starts at 0). But, this is assuming that the user selected all 5 colors. If he only selected 2 of them, we would only have

$color[0]
$color[1]

Take note that if the user selected the first and last color in the list (which was red and violet), we would not end up with $color[0] and $color[4]. Which is good. PHP automatically makes the array in order with no gaps. It makes it easier for processing.

so that 0,1,2,3,4 is the array's keys. each key points to each color the user selected (officially it's called a value. key points to value). so if the user selected red and violet, you could do this:

echo $color[0];
echo "<br>";
echo $color[1];

and you would see this on the screen:

red
violet

but that's not very convenient, especially if you have a long list of checkboxes. Imagine having to type out all those echo's over and over for 10 colors, or 100 or thousands. This is where the convenience of arrays come in. Remember, an array is nothing more than a group of variables all under the same name, with neat little keys that go in numerical order. And since these keys are conveniently in order and conveniently they are numeric, we can just create a loop that cycles through all of them.

we can use a for loop if we knew exactly how many values were in the array, but since we aren't psychic and therefore we don't know how many checkboxes the user will check, we would use a while loop.

this is what listcolors.php is looking like so far:
if ($_POST['color']) {
   $color = $_POST['color'];

   $count = 0;
   while ($color[$count]) {
      echo $color[$count];
      echo "<br>";
      $count++;  
   }
} else {
   echo "you did not select any colors!";
}

The if($_POST{'color']) { .... } simply checks to see if the user selected any colors. if they did not, then it will print "you did not select any colors!"

then we make the $color array. Then we will make a new variable called $count, which we will start at 0 because the array keys start at 0. then the while loop simply says this: While there is a value for the key, print the value that the key points to. Then we increment $count by one and repeat the while loop.

so if the user were to check red and violet, the while loop will start out by echoing $color[0] (red) and then $count will then count up to 1, and then $color[1] will be echoed (violet), then $count will go up to 2. since there is no $color[2] because the user did not select 3 colors, the while loop stops.

I hope that this somehow helps you have a better understanding of what the []'s mean in the form names and how arrays work. There is much much more to arrays than simply this, though. You can do all sorts of things to re-arrange the order of the values, have arrays inside arrays, name your keys, etc.. but that's another discussion.
Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)

#11 danthethug

danthethug
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 15 May 2006 - 03:16 PM

Thank you all, I tried the example redbullmarky had given me which was:

$sql = "delete from users where ";
$checkboxarray = $_POST['remove'];

foreach ($checkboxarray as $value)
{
   $sql.= "username = '$value' OR ";
}

I then edited the code to fit my needs but it Still didnt work so i did the following:

$checkboxarray = $_POST['remove'];

foreach ($checkboxarray as $value)
{
   $sql= "DELETE FROM `User_Hitlist` WHERE ID='$value'";
mysql_query("$sql");
}

And that worked out fine, Thanks again all. I loved the fast replies, Will be back when i have another problem :).

#12 danthethug

danthethug
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 15 May 2006 - 04:35 PM

I have a new problem relating a Message Center ive added awhile ago. Im trying to implement the Checkbox Arrays with this.

Im getting the following error:

Warning: Invalid argument supplied for foreach() in /home/nuke/public_html/Reloaded/message.php on line 12

Here is the PHP Code:



<?

if ($del) {
$checkboxarray3 = $_POST['delid'];

foreach ($checkboxarray3 as $value3)
{
   $sql3= "DELETE FROM `Mail` WHERE Id='$value3'";
mysql_query("$sql3");
}

print "Deleted";

}

?>


Line 12 is right where foreach() is.

I dont know whats wrong with it, Seems just fine but its not working.

#13 redbullmarky

redbullmarky
  • Staff Alumni
  • Advanced Member
  • 2,863 posts
  • LocationBedfordshire, England

Posted 15 May 2006 - 06:39 PM

that would suggest that $checkboxarray3 is not an array, so backtracking a bit it also could mean $_POST['delid'] is not an array either. if 'delid' is a group of checkboxes, as with your other example, make sure you've got them set up with the [] as before

<input name="delid[]" etc etc etc

it could also mean that the condition you're checking for here:

if ($del) {
   $checkboxarray3 = $_POST['delid'];
is not actually being met, which is the most likely answer considering i can't see where $del is being set in the first place.

with the above code, basically you're saying that if $del is 'true' or a non-zero value, set up the $checkbox3array and then do a 'foreach' on it. but if $del is false or a zero value, then you dont set up the array but run the foreach anyway.

hope that helps

cheers
Mark
"you have to keep pissing in the wind to learn how to keep your shoes dry..."

I say old chap, that is rather amusing!

#14 danthethug

danthethug
  • New Members
  • Pip
  • Newbie
  • 9 posts

Posted 15 May 2006 - 07:28 PM

[!--quoteo(post=374082:date=May 15 2006, 02:39 PM:name=redbullmarky)--][div class=\'quotetop\']QUOTE(redbullmarky @ May 15 2006, 02:39 PM) View Post[/div][div class=\'quotemain\'][!--quotec--]
that would suggest that $checkboxarray3 is not an array, so backtracking a bit it also could mean $_POST['delid'] is not an array either. if 'delid' is a group of checkboxes, as with your other example, make sure you've got them set up with the [] as before

<input name="delid[]" etc etc etc

it could also mean that the condition you're checking for here:

if ($del) {
   $checkboxarray3 = $_POST['delid'];
is not actually being met, which is the most likely answer considering i can't see where $del is being set in the first place.

with the above code, basically you're saying that if $del is 'true' or a non-zero value, set up the $checkbox3array and then do a 'foreach' on it. but if $del is false or a zero value, then you dont set up the array but run the foreach anyway.

hope that helps

cheers
Mark
[/quote]

Yep it does, Ima try to check and see if its getting the ID of the messages to the Variable.

Below is where it is defining the Variable $delid:

<input type="checkbox" name="delid[]" value="<? print "$wep[Id]"; ?>">

Thats just a snippet.

Ok, Ive figured the problem out, (D' oh) I had forgotten to allow the <form method="post"> to be above the checkbox to carry the information. [img src=\"style_emoticons/[#EMO_DIR#]/laugh.gif\" style=\"vertical-align:middle\" emoid=\":laugh:\" border=\"0\" alt=\"laugh.gif\" /] [img src=\"style_emoticons/[#EMO_DIR#]/laugh.gif\" style=\"vertical-align:middle\" emoid=\":laugh:\" border=\"0\" alt=\"laugh.gif\" /]

#15 .josh

.josh
  • Staff Alumni
  • .josh
  • 14,871 posts

Posted 15 May 2006 - 10:43 PM

concerning your code that you fixed before:
$checkboxarray = $_POST['remove'];

foreach ($checkboxarray as $value)
{
   $sql= "DELETE FROM `User_Hitlist` WHERE ID='$value'";
mysql_query("$sql");
}
use this piece of code instead:
$sql ="DELETE FROM 'User_Hitlist' WHERE ID IN (";
foreach ($checkboxarray as $value) {
   $sql.="'$value',";
}
$sql = substr_replace($sql,"",-1);          
$sql.= ")";

mysql_query($sql) or die(mysql_error());

what this does is use the sql keyword "IN" to check against several values at once. Example:

[!--coloro:blue--][span style=\"color:blue\"][!--/coloro--]delete from user_hitlist where id in (1,2,3)[!--colorc--][/span][!--/colorc--]

will delete all rows in the table where id = 1,2 or 3

the substr_replace simply takes off the last comma generated in the foreach loop. The reason you should do it this way, is because you only have to run one query. The less queries, the better.
Did I help you? Feeling generous? Buy me lunch! 
Please, take the time and do some research and find out how much it would have cost you to get your help from a decent paid-for source. A "roll-of-the-dice" freelancer will charge you $5-$15/hr. A decent entry level freelancer will charge you around $15-30/hr. A professional will charge you anywhere from $50-$100/hr. An agency will charge anywhere from $100-$250/hr. Think about all this when soliciting for help here. Think about how much money you are making from the work you are asking for help on. No, we do not expect you to pay for the help given here, but donating a few bucks is a fraction of the cost of what you would have paid, shows your appreciation, helps motivate people to keep offering help without the pricetag, and helps make this a higher quality free-help community :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users