View Full Version : Updating tables with foreach

04-20-2011, 08:40 AM
$q = "SELECT * FROM table WHERE current_month_end <= NOW()";
$r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

$num = mysqli_num_rows($r);

$row = mysqli_fetch_array($r, MYSQLI_ASSOC);

if($num > 0) //We have some expired campaigns
$amt[] = $roww;

foreach($amt as $nu)
//Update each row

I want to update every row that meets the queries requirements. However, what's the best way to call each row. Do I need to put a WHERE clause in this query or not. For instance, in the foreach loop which is correct:

$q = "SELECT * FROM table WHERE current_month_end <= NOW()";

which is the same query as the original. Or is it without a WHERE clause since that was already established before the foreach loop. Like this:

$q = "SELECT * FROM table";

Will that second one just end up updating every single row in table? Or maybe neither of those is the correct. Thanks for any help

04-20-2011, 10:54 AM
I actually got it doing what I needed it to do. But I'm having a problem with the foreach loop, i'm getting the following error:

Warning: Invalid argument supplied for foreach() in check.php on line 20

It worked the first time I ran it, then I ran it a second time and i got that error, even when $num was greater than 0.... :confused:

is there a glaring problem i'm missing?


After doing a few more tests, here's a little more info. When clearly $num has 3 or 4 returns, when it runs through the foreach loop, it only does 1, then when I try to run it again I get that error. So it's working, I just have a problem in where something is located, any help is appreciated, thanks.