开发者

Problem with foreach () Invalid Argument Supplied

I am trying to delete every follower from an array using PHP. However I am receiving the error :

Warning: Invalid argument supplied for foreach() in /home/nucleusi/public_html/maxkdevelopment.co.uk/SocialPic/socialPic.php

Please can you tell me where I am going wrong?

$arg = mysql_query("SELECT `followerUserID` FROM Following 
   WHERE `followingUserID` = '$id'") or die("1. " . mysql_error());
$array = mysql_fetch_array($arg);
foreach($array['followerUserID'] as $accID) {
  mysql_query("UPDATE Accounts SET `Following Count` = (`Following Count`-1) 
    WHERE `id` = '$accID'") or die("2. " . mysql_error());
}
$arg = mysql_query("SELECT `followingUserID` FROM Following 
  WHERE `followerUserID` = '$id'") or die("3. " . mysql_error());
$array = mysql_fetch_array($arg);
foreach($ar开发者_运维百科ray['followingUserID'] as $accID) {
  mysql_query("UPDATE Accounts SET `Followed Count` = (`Followed Count`-1) 
    WHERE `id` = '$accID'") or die("4. " . mysql_error());
}


MySQL will not return arrays in a field, indexing an array retrieved from a query will return a single field, and foreach() expects an array. What you have written cannot work. Use a while() loop to iterate through the query results as one would normally do.


foreach requeries an array, maybe you are not getting an array from your queries. Add the function is_array a do var_dump when it is not an array to see what is happening.

http://php.net/manual/en/function.is-array.php



while ($row = mysql_fetch_array($arg)) 
{

}


You can do this query in one go without needing foreach loops:

The first one can be compressed into:

UPDATE Accounts SET `Following Count` = (`Following Count`-1) 
INNER JOIN Following f ON (f.followingUserID = accounts.id)
WHERE F.followingUserId = '$id'

And the second one as well.

UPDATE Accounts SET `Followed Count` = (`Followed Count`-1) 
INNER JOIN Following f ON (f.followingUserID = accounts.id)
WHERE F.followerUserId = '$id'

Now you don't need that loop anymore.


this problem is often caused because the array is empty. e.g. the array has no items in it so when you do the foreach the server cant process anything and returns the error.

what you can do is check if the array is empty first and then do your foreach if you know you have at least one item in your array.

like so:

if(empty($yourArray))
{echo"<p>There's nothing in the array.....</p>";}
else
{
foreach ($yourArray as $current_array_item)
{
//do something with the current array item here
} 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜