Reputation: 19
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";
}
}
}
Upvotes: 0
Views: 75
Reputation: 2305
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();
}
}
Upvotes: 0
Reputation: 23759
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";
}
}
Upvotes: 1