Home > Software design >  if/elseif/else statement not working as it should
if/elseif/else statement not working as it should

Time:10-05

As the title says I have a problem running an if/elseif/else statement query, long story short it's not entering the condition correctly.

Here is the PHP code

<?php 

$time = $_SERVER['REQUEST_TIME'];
$query0 = "SELECT lastco FROM customers";
$query_run0 = mysqli_query($conn, $query0);

if(mysqli_num_rows($query_run0) > 0)
{
    while($row = mysqli_fetch_assoc($query_run0))
    {
        if($row['lastco'] < $time-300)
        {
            if($row['lastco'] < $time-2000000)
            {
                $query1 = "UPDATE customers SET customer_status='Not Registered' WHERE lastco < $time-2000000";
                $query_run1 = mysqli_query($conn, $query1);
            }
            else
            {
                $query2 = "UPDATE customers SET customer_status='Offline' WHERE lastco < $time-300";
                $query_run2 = mysqli_query($conn, $query2);
            }
            
        }
        elseif($row['lastco'] > $time-300)
        {
            $query3 = "UPDATE customers SET customer_status='Online' WHERE lastco > $time-300";
            $query_run3 = mysqli_query($conn, $query3);
        }
    }
}?>

So the problem is that instead of modifying the customer_status row to 'Not Registered' it will just modify it to 'Offline', and never edit the row to 'Not Registered' even if the condition is fulfilled so what can I do to make that statement work that way ?

CodePudding user response:

Your if conditions works just fine. Instead of defaulting to the assumption that if is somehow broken, examine your logic. Start by putting that logic into simple descriptions:

For *every record*, repeat:
  If some value is below 300
    If some value is below 2000000
      Update *all values* that are below 2000000
    Else
      Update *all values* that are below 300
  Else, if some value is above 300
    Update *all values* that are above 300

So... If each iteration of the loop is meant to update all values, then why do you need to repeat that operation in a loop at all?

And, more to the point here... When you Update *all values* that are below 300, why do you expect that wouldn't also Update *all values* that are below 2000000? After all, any number which is lower than 300 is also lower than 2000000.

Scrap the loop and all the if/else blocks entirely. Just perform the updates you want to perform:

Update *all values* that are below 2000000
Update *all values* that are below 300
Update *all values* that are above 300

Forget the SELECT, forget the loop, just execute your three UPDATE statements to update your data. (You could do it in one UPDATE statement, but for clarity let's just start with removing all the cruft of that loop.)

  • Related