简体   繁体   中英

Only run php function once

I have this php function which checks a table in a database and checks to see if a user has a specific number in a field . This user could have a few rows where that filed has that number .

The problem with this is that it will run the if statement multiple times, triggering the resulting function to run multiple times. How can I stop this and just have the function say "okay found a match for al1 and running function , moving onto al2"

function countNewBadges() {
    require "connect.php"; 

    $count = mysqli_query($connection,"SELECT users.studentid, al1, al2, al3 FROM userbadges ub INNER JOIN users ON users.id = ub.user_id WHERE studentid = '".$_SESSION["studentid"]."'")  or die(mysqli_error($connection));

    while ($data = mysqli_fetch_array($count)) { 

    if ($data['al1'] == 1)
    { 
        unlockedBadges();
    }
    else if ($data['al2'] == 1)
    {
        echo "No New Badges";
    }
    else if ($data['al3'] == 1)
    {
        echo "No New Badges";
    }
}
}

How can I have the function say "okay found a match for al1 and running function, moving onto al2"

Just use a flag variable:

$flag = false;
while ($data = mysqli_fetch_array($count)) { 

    if ($data['al1'] == 1 && $flag === false)
    { 
        unlockedBadges();
        $flag = true;
    }
    else if ($data['al2'] == 1)
    {
        echo "No New Badges";
    }
    else if ($data['al3'] == 1)
    {
        echo "No New Badges";
    }
}

While user4035's answer will stop multiple data entries to truly only run a function once you need to search and then act after (using as was said) a flag.

function countNewBadges() {
    require "connect.php"; 

    $count = mysqli_query($connection,"SELECT users.studentid, al1, al2, al3 FROM userbadges ub INNER JOIN users ON users.id = ub.user_id WHERE studentid = '".$_SESSION["studentid"]."'")  or die(mysqli_error($connection));

    $foundit=false;

    while ($data = mysqli_fetch_array($count)) { 

        if ($data['al1'] == 1)
        { 
            $foundit=true;
        }
        else if ($data['al2'] == 1)
        {
            echo "No New Badges";
        }
        else if ($data['al3'] == 1)
        {
            echo "No New Badges";
        }
    }
    if($foundit){
        unlockedBadges();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM