Jump to content

foreach error? Need help.


Kristian_C

Recommended Posts

Hello. Im working on a online text based "mafia" game. And in the inbox system when ppl wants to delete more then one message, with checkboxes. and than click Delete Selected. But then this ugly message comes up : Warning: Invalid argument supplied for foreach() in /home/mafia/public_html/wildmafia/Test.php on line 168messages deleted but are they deleted? No absolutly not :) so i just need to know what that foreach() thing is :) anyone online now that knows what it is and what it does? a little bit more info :

if (strip_tags($_POST['D_s'])){foreach ($_POST['radio'] as $value) {   $count++;mysql_query("DELETE FROM inbox WHERE id='$value'");} echo "$count messages deleted<br>";}

lol, tried to remove foreach , and guess what :) i think someone is messing with me.. foreach dident need to be there :blink: hehe.. But still wont delete?removed foreach and set "if" there insted.. is that correct?

Link to comment
Share on other sites

foreach is used to parse through elements of an array.Thus, it's expecting $_POST['radio'] to be an array. It then cycles though each element of that array, setting the value of the element to $value. I'm assuming you're deleting multiple messages (I mean, that count is there), so you need that foreach. I'd go look at your html and make sure that the form is returning an array into 'radio'.

Link to comment
Share on other sites

To expand on that a little bit, an array is a collection of items. $_POST is an array, it is a collection of the information that was submitted from a form using the post method. Foreach is one way to loop through the collection and get each item from it. If you have an array called $nums that has a list of numbers, this loop will print each one:

<?php$nums = array (1, 2, 3, 4, 5);foreach ($nums as $num){  print $num;  //prints 12345}?>

You can also use foreach with an array that has names for keys instead of numbers.

<?php$nums = array ("one" => 1, "two" => 2, "three" => 3);foreach ($nums as $key => $val){  print $key . " equals " . $val . "\n";}/*output:one equals 1two equals 2three equals 3*/?>

So you have a list of items that you want to delete, and it looks like each one has a unique ID. You will probably want to use a list of checkboxes. The checkboxes should all be named as an array, and each one has the value of an ID. So then you can loop through the array using foreach and delete all of them.You would want to use a loop to print out all of your checkboxes (if you aren't already)

<?php$result = mysql_query("SELECT * FROM inbox");while ($row = mysql_fetch_assoc($result)){  ...  echo "<input type=\"checkbox\" name=\"delete_ids[]\" value=\"{$row['id']}\" />";  ...}?>

The [] after the name makes the variable delete_ids an array. So now you get the array in PHP and loop through it to get each ID to delete:

<?php$delete_ids = $_POST['delete_ids'];if (is_array($delete_ids) && count($delete_ids) > 0){  $id_list = "";  foreach ($delete_ids as $id)  {	if ($id_list != "")	  $id_list .= ",";	$id_list .= $id;  }  mysql_query("DELETE FROM inbox WHERE id IN ($id_list)");}?>

Link to comment
Share on other sites

  • 1 month later...

Hey, sorry for useing so long time on answering :) but allmost forgot about it, but now it have become a problem again as i am working on a new game.I added ("allmost copyed") your code :) but it dont work :s... It deletes but it just deletes one or two messages and it wont delete the oldest message in the inbox : Heres the code :

  <?$mysql1 = mysql_query("SELECT * FROM `inkom` WHERE `til`='$brukernavn' AND `lagra` ='no' ORDER by tid DESC");$antall =mysql_num_rows($mysql1);if ($antall == "0"){echo "<table with='60%' hight='15' bordercolor='000000' border='1' align=center><tr><td background=link.jpg><font color='ffffff'>You have no mail.</font></tr></td></table>";}else{while($inkom = mysql_fetch_object($mysql1)){$row = mysql_fetch_assoc($mysql1);$t++;$n++;?>  <table width='77%'  border='1' align='center' cellspacing='0' bordercolor='010101'>	<tr>	  <td background='link.jpg' width='31%'><? if($inkom->lest=="no"){echo"Unread :"; } echo"<a href=?side=lesmeld&meld=$inkom->id>$inkom->tittel</a>"; ?>	  </td>	  <td background='link.jpg' width='34%'><? echo" $inkom->fra"; ?> </td>	  <td background='link.jpg' width='28%'><? echo" $inkom->tid"; ?> </td>	  <td background='link.jpg' width='7%'><?php  echo "<input type=\"checkbox\" name=\"delete_ids[]\" value=\"{$row['id']}\" />";?></td>	</tr>  </table>  <?}}?><table width="10%" height="30"  border="0" align="center" cellspacing="1">	 <tr>	   <th scope="col"><table width="38%"  border="0" cellspacing="1">		 <tr>		   <th width="50%" scope="col"><input name="slettalle" type="submit" class="button" id="slettalle" value="Delete All"></th>		   <th width="50%" scope="col"><input name="slettsel" type="submit" class="button" id="slettsel" value="Delete Selected"></th>		 </tr>	   </table></th>	 </tr>   </table> </form> <?phpif($_POST['slettsel']){$delete_ids = $_POST['delete_ids'];if (is_array($delete_ids) && count($delete_ids) > 0){  $id_list = "";  foreach ($delete_ids as $id)  {	if ($id_list != "")	  $id_list .= ",";	$id_list .= $id;  }  mysql_query("DELETE FROM inkom WHERE id IN ($id_list)");}}?></body></html>

If you can help me out again it whould be great :)-> Kristian_C

Link to comment
Share on other sites

I think this is your problem:while($inkom = mysql_fetch_object($mysql1)){$row = mysql_fetch_assoc($mysql1);The first line gets the next row from the result and stores it in the object $inkom. The next line gets the next row from the result and stores it in the array $row. So these two lines get two different rows from the database, so you're getting two rows at once instead of one at a time. So the second time through the loop, you will get rows 3 and 4 instead of row 2. Remove the second line and have them all use the $inkom object.

Link to comment
Share on other sites

Well fixed it, but still dont work :sif you have any more ideas of whats wrong feel free to tell :) Code now :

<?phpif($_POST['slettsel']){$delete_ids = $_POST['delete_ids'];if (is_array($delete_ids) && count($delete_ids) > 0){  $id_list = "";  foreach ($delete_ids as $id)  {	if ($id_list != "")	  $id_list .= ",";	$id_list .= $id;  }$utkom=count($delete_ids);  mysql_query("DELETE FROM inkom WHERE id IN ($id_list)");echo"$utkom messages deleted";}}?><table width="82%"  border="1" align="center" cellspacing="0" bordercolor="010101">  <tr>	<th background="grad.jpg" colspan="4" scope="col"><strong>Inbox </strong></th>  </tr>  <tr>	<td background="link.jpg" width="31%">Title</td>	<td background="link.jpg" width="32%">From</td>	<td background="link.jpg" width="22%">Time sent </td>	<td background="link.jpg" width="15%">Delete</td>  </tr></table><?$mysql1 = mysql_query("SELECT * FROM `inkom` WHERE `til`='$brukernavn' AND `lagra` ='no' ORDER by tid DESC");$antall =mysql_num_rows($mysql1);if ($antall == "0"){echo "<table with='60%' hight='15' bordercolor='000000' border='1' cellspacing='0' align=center><tr><td background=link.jpg><font color='ffffff'>You have no mail.</font></tr></td></table>";}else{while($inkom = mysql_fetch_object($mysql1)){$t++;$n++;?><table width='82%'  border='1' align='center' cellspacing='0' bordercolor='010101'>  <tr>	<td background='link.jpg' width='31%'><? if($inkom->lest=="no"){echo"Unread :"; } echo"<a href=?side=lesmeld&meld=$inkom->id>$inkom->tittel</a>"; ?> </td>	<td background='link.jpg' width='32%'><? echo" $inkom->fra"; ?> </td>	<td background='link.jpg' width='22%'><? echo" $inkom->tid"; ?> </td>	<td background='link.jpg' width='15%'><? echo "<input type='checkbox' name='delete_ids[]' value='$inkom->id'>"; ?></td>  </tr></table><?}}?><?if($_POST['slett']){mysql_query("DELETE FROM inkom WHERE lest='yes' AND lagra='no' AND til='$brukernavn'") or die('Error :' .mysql_error());echo"All messages deleted";}if($_POST['save']){mysql_query("UPDATE inkom SET lagra='yes' WHERE til='$brukernavn'") or die('Error :' .mysql_error());echo"All messages saved";}?><form name="form1" method="post" action="">  <table width="38%"  border="1" align="center" cellspacing="0" bordercolor="010101" bgcolor="121212">	<tr>	  <th scope="col"><input name="slett" type="submit" class="button" id="slett" value="Delete all">	  <input name="save" type="submit" class="button" id="save" value="Save all"> <input name="slettsel" type="submit" class="button" id="slettsel" value="Delete Selected"></th>	</tr>  </table></form>

->Kristian_C.

Link to comment
Share on other sites

It's got to do something. There aren't any exit or die statements, so it's got to be doing something. You should at least see the header table. If you don't see anything, then you may be getting an error with display_errors disabled. If that's the case, then you would need to enable errors to see what the error message is. Or else, you should start putting in debugging statements to see where the execution flow is going.

Link to comment
Share on other sites

It's got to do something. There aren't any exit or die statements, so it's got to be doing something. You should at least see the header table. If you don't see anything, then you may be getting an error with display_errors disabled. If that's the case, then you would need to enable errors to see what the error message is. Or else, you should start putting in debugging statements to see where the execution flow is going.
It was doing something after i did the little change :) But the thing i forgot to do after i added the chekboxes in the rows was to stretch the from from the top to the bottom, so the checkboxes was actually not inside the from :) hehe...Thanks for helping me out with that one :)Works perfect! :)So off to the next checkbox problem :) Now i need to get the value from sql then update another table with the value from the other table then delete from the table :blink: Ill just try to make it work before i post a code and stuff :blink: ->Kristian_C
Link to comment
Share on other sites

ok, i tried this :

if($_POST['slettsel']){$delete_ids = $_POST['delete_ids'];if (is_array($delete_ids) && count($delete_ids) > 0){  $id_list = "";  foreach ($delete_ids as $id)  {	if ($id_list != "")	  $id_list .= ",";	$id_list .= $id;  }$utkom=count($delete_ids);$kk=mysql_query("SELECT * FROM biler WHERE id IN ($id_list)");$jjjs=mysql_fetch_object($kk);mysql_query("UPDATE brukere SET penger=penger+'$jjjs->pris' WHERE brukernavn='$brukernavn'") or die('Error : ' .mysql_error());  mysql_query("DELETE FROM biler WHERE id IN ($id_list)");echo"$utkom cars sold";}}

but it didet work, also tried to select sum(pris) as total but dident work...any ideas?->Kristian_C.

Link to comment
Share on other sites

this is something ill remember for a loong while now that i have learnd abit about it :lol, tried to remove foreach , and guess what i think someone is messing with me.. foreach dident need to be there hehe.. But still wont delete?removed foreach and set "if" there insted.. is that correct?:) ----------good reminder about us all beeing "noobs" back in the times :) hehe.. pretty funny :) ->Kristian_C.

Link to comment
Share on other sites

You do need some sort of loop. Removing the loop in this case will cause the string of IDs to delete to not be created, so nothing will be deleted. It sounds like you aren't understanding what is happening or what needs to happen, but it's pretty simple. The goal is to produce a SQL query that looks something like this:DELETE FROM table WHERE id IN (1, 2, 3, 5, 7, 10, 12)That statement will delete all rows where the ID is one of those numbers listed.So, the question is how to produce that SQL statement. If you have several checkboxes like this:<input type="checkbox" value="1" name="delete_ids[]"><input type="checkbox" value="2" name="delete_ids[]"><input type="checkbox" value="3" name="delete_ids[]">Then people can select whatever they want, say the first and last boxes, and since the values are listed as 1 and 3, and the name is delete_ids[], when they hit submit PHP will have access to an array called $_POST['delete_ids'] and the array will contain the values 1 and 3 in the first and second indexes. This is what you want, you have a list of IDs corresponding to the boxes that they checked to delete.So, at this point that is what you have, an array of IDs to delete. There are two ways to process that array. Either you can loop through the array and perform a DELETE query for each ID, but for an array of 50 IDs that would cause 50 queries to the server. It's not efficient. A better way is to build up a list of IDs, and then send one query to the server to delete them all (like the SQL query above). So, the question is how to build a comma-separated list of all of the IDs in the $_POST['delete_ids'] array. There are two ways to do that. The first is to use a loop such as for, while, or foreach to build it:

$id_list = ""; //start empty//for loop:for ($i = 0; $i < count($_POST['delete_ids']); $i++){  if ($id_list != "") //if there is already an ID in the list	$id_list .= ","; //add a comma  $id_list .= $_POST['delete_ids'][$i]; //add the current ID}//while loop:$i = 0;while ($i < count($_POST['delete_ids'])){  if ($id_list != "") //if there is already an ID in the list	$id_list .= ","; //add a comma  $id_list .= $_POST['delete_ids'][$i]; //add the current ID  $i++;  //go to the next ID}//foreach loopforeach ($_POST['delete_ids'] as $id){  if ($id_list != "") //if there is already an ID in the list	$id_list .= ","; //add a comma  $id_list .= $id; //add the current ID}

The end result of any of those three loops is to cause $id_list to contain a comma-separated list of the IDs found in the $_POST['delete_ids'] array. There is also a shortcut for doing this, since joining elements in an array is a common task. The implode function does this:

$id_list = implode(",", $_POST['delete_ids']);

That will do the same thing, the array $_POST['delete_ids'] is joined with comma characters, creating a comma-separated list of IDs.Now that $id_list has a list of all of the IDs to delete, from however you chose to do that, now you can substitute it into the SQL query to delete all records corresponding to those IDs:

mysql_query("SELECT * FROM biler WHERE id IN ($id_list)");

You can print that SQL statement or print $id_list to verify that this is true. So, hopefully that gets you in the right direction. All this problem is is that you need to create a comma-separated list from an array of numbers and substitute that list into a SQL query. Any of the 4 methods I showed above will create that list for you.

Link to comment
Share on other sites

Hey :

Now i tried the code, and it works to delete, but it dont count more then one from the list, in another way  i can just delete but not get the ammount i try to select, so my problem is still to get ammount from list. $id_list = implode(",", $_POST['delete_ids']);tried this :$sellmange=mysql_query("SELECT pris FROM biler WHERE id IN ($id_list)");mysql_query("UPDATE brukere SET penger=penger+'$sellmange' WHERE brukernavn='$brukernavn'") or die('Error : ' .mysql_error());echo"Cars sold";mysql_query("DELETE FROM biler WHERE id IN ($id_list)") or die('Error : ' .mysql_error());} and this :$sellmange=mysql_query("SELECT sum(pris) AS total FROM biler WHERE id IN ($id_list)");mysql_query("UPDATE brukere SET penger=penger+'$sellmange' WHERE brukernavn='$brukernavn'") or die('Error : ' .mysql_error());echo"Cars sold";mysql_query("DELETE FROM biler WHERE id IN ($id_list)") or die('Error : ' .mysql_error());} and this :$sellmange=mysql_query("SELECT * FROM biler WHERE id IN ($id_list)");$mysql=mysql_fetch_object($sellmange);mysql_query("UPDATE brukere SET penger=penger+'$mysql->pris' WHERE brukernavn='$brukernavn'") or die('Error : ' .mysql_error());echo"Cars sold";mysql_query("DELETE FROM biler WHERE id IN ($id_list)") or die('Error : ' .mysql_error());}But nothing seems to work :s any ideas?

->Kristian_C.

Link to comment
Share on other sites

It's hard for me to tell what you want with the column names in a language I don't speak, but if you want to get the sum of the pris column or the number of rows then it would be one of these:$sellmange=mysql_query("SELECT SUM(pris) AS val FROM biler WHERE id IN ($id_list)");$sellmange=mysql_query("SELECT COUNT(pris) AS val FROM biler WHERE id IN ($id_list)");And then to access the value that you had returned:$row = mysql_fetch_assoc($sellmange);$num = $row['val'];Now the variable $num would contain either the sum of all of the values in the pris column (the first query above), or the number of rows that match the id list (the second query).

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...