danthethug Posted May 14, 2006 Share Posted May 14, 2006 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:[code] <td align="center" bgcolor="#0E0E17"><input type="checkbox" name="remove[]" value="<? print "$wep[ID]"; ?>"></td>[/code]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. Quote Link to comment Share on other sites More sharing options...
redbullmarky Posted May 14, 2006 Share Posted May 14, 2006 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:[code]$checkboxarray = $_POST['remove'];[/code]hope that helps. Quote Link to comment Share on other sites More sharing options...
danthethug Posted May 14, 2006 Author Share Posted May 14, 2006 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:[code]<?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>[/code]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! Quote Link to comment Share on other sites More sharing options...
redbullmarky Posted May 14, 2006 Share Posted May 14, 2006 that's because you have to treat an array as such.[code]$test = array('a', 'b', 'c');echo $test; // output is 'Array'echo $test[1]; // output is 'b'print_r($test); // output is the full array[/code]so you need to go through each of your array elements and process them, for example:[code]$sql = "delete from users where ";$checkboxarray = $_POST['remove'];foreach ($checkboxarray as $value){ $sql.= "username = '$value' OR ";}[/code]that should give you an ideacheersMark Quote Link to comment Share on other sites More sharing options...
danthethug Posted May 14, 2006 Author Share Posted May 14, 2006 [!--quoteo(post=373712:date=May 14 2006, 08:04 AM:name=redbullmarky)--][div class=\'quotetop\']QUOTE(redbullmarky @ May 14 2006, 08:04 AM) [snapback]373712[/snapback][/div][div class=\'quotemain\'][!--quotec--]that's because you have to treat an array as such.[code]$test = array('a', 'b', 'c');echo $test; // output is 'Array'echo $test[1]; // output is 'b'print_r($test); // output is the full array[/code]so you need to go through each of your array elements and process them, for example:[code]$sql = "delete from users where ";$checkboxarray = $_POST['remove'];foreach ($checkboxarray as $value){ $sql.= "username = '$value' OR ";}[/code]that should give you an ideacheersMark[/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]"; ?>"? Quote Link to comment Share on other sites More sharing options...
redbullmarky Posted May 14, 2006 Share Posted May 14, 2006 [!--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) [snapback]373713[/snapback][/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. Quote Link to comment Share on other sites More sharing options...
danthethug Posted May 14, 2006 Author Share Posted May 14, 2006 [!--quoteo(post=373720:date=May 14 2006, 08:50 AM:name=redbullmarky)--][div class=\'quotetop\']QUOTE(redbullmarky @ May 14 2006, 08:50 AM) [snapback]373720[/snapback][/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? Quote Link to comment Share on other sites More sharing options...
redbullmarky Posted May 14, 2006 Share Posted May 14, 2006 [!--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) [snapback]373723[/snapback][/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. Quote Link to comment Share on other sites More sharing options...
danthethug Posted May 14, 2006 Author Share Posted May 14, 2006 [!--quoteo(post=373727:date=May 14 2006, 09:26 AM:name=redbullmarky)--][div class=\'quotetop\']QUOTE(redbullmarky @ May 14 2006, 09:26 AM) [snapback]373727[/snapback][/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 Quote Link to comment Share on other sites More sharing options...
.josh Posted May 14, 2006 Share Posted May 14, 2006 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 [b]remove[/b] 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:[code]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>[/code]the user can check whichever colors (s)he likes and click the submit button. Clicking the submit button will send the array [b]colors[/b] (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:redvioletbut 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:[code]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!";}[/code]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. Quote Link to comment Share on other sites More sharing options...
danthethug Posted May 15, 2006 Author Share Posted May 15, 2006 Thank you all, I tried the example redbullmarky had given me which was:[code]$sql = "delete from users where ";$checkboxarray = $_POST['remove'];foreach ($checkboxarray as $value){ $sql.= "username = '$value' OR ";}[/code]I then edited the code to fit my needs but it Still didnt work so i did the following:[code]$checkboxarray = $_POST['remove'];foreach ($checkboxarray as $value){ $sql= "DELETE FROM `User_Hitlist` WHERE ID='$value'";mysql_query("$sql");}[/code]And that worked out fine, Thanks again all. I loved the fast replies, Will be back when i have another problem :). Quote Link to comment Share on other sites More sharing options...
danthethug Posted May 15, 2006 Author Share Posted May 15, 2006 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 12Here is the PHP Code:[code]<?if ($del) {$checkboxarray3 = $_POST['delid'];foreach ($checkboxarray3 as $value3){ $sql3= "DELETE FROM `Mail` WHERE Id='$value3'";mysql_query("$sql3");}print "Deleted";}?>[/code]Line 12 is right where foreach() is.I dont know whats wrong with it, Seems just fine but its not working. Quote Link to comment Share on other sites More sharing options...
redbullmarky Posted May 15, 2006 Share Posted May 15, 2006 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 etcit could also mean that the condition you're checking for here:[code]if ($del) { $checkboxarray3 = $_POST['delid'];[/code]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 helpscheersMark Quote Link to comment Share on other sites More sharing options...
danthethug Posted May 15, 2006 Author Share Posted May 15, 2006 [!--quoteo(post=374082:date=May 15 2006, 02:39 PM:name=redbullmarky)--][div class=\'quotetop\']QUOTE(redbullmarky @ May 15 2006, 02:39 PM) [snapback]374082[/snapback][/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 etcit could also mean that the condition you're checking for here:[code]if ($del) { $checkboxarray3 = $_POST['delid'];[/code]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 helpscheersMark[/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:[code]<input type="checkbox" name="delid[]" value="<? print "$wep[Id]"; ?>">[/code]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\" /] Quote Link to comment Share on other sites More sharing options...
.josh Posted May 15, 2006 Share Posted May 15, 2006 concerning your code that you fixed before:[code]$checkboxarray = $_POST['remove'];foreach ($checkboxarray as $value){ $sql= "DELETE FROM `User_Hitlist` WHERE ID='$value'";mysql_query("$sql");}[/code]use this piece of code instead:[code]$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());[/code]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 3the 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.