Reputation: 24481
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($array['followingUserID'] as $accID) {
mysql_query("UPDATE Accounts SET `Followed Count` = (`Followed Count`-1)
WHERE `id` = '$accID'") or die("4. " . mysql_error());
}
Upvotes: 0
Views: 250
Reputation: 191
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
}
}
Upvotes: 0
Reputation: 76547
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.
Upvotes: 0
Reputation: 1466
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
Upvotes: 1
Reputation: 798576
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.
Upvotes: 1