After your INSERT
statement, you can add continue 2
to bring you back to the top of your foreach ($ex as ...
. You can also use break;
in this case because there's nothing after your inner while
.
However, you don't actually need it if you do it differently. Instead of reading the table for each privilege, just read all of them once and them compare.
This code will get all privileges from the database and then only inserts those that are missing, based on $ex
; it uses array_diff()
to calculate the difference between the two.
public static function insertPriveleges($user_id, $priveleges)
{
$ex = explode(",", $priveleges); // separated by commas
if (count($ex) > 0) {
// get user's current priveleges
$check_user = mysql_query("SELECT * FROM users_access_codes
WHERE user_id='$user_id'") or die(mysql_error());
$actual = array();
while ($row = mysql_fetch_array($check_user)) {
$actual[] = $row['access_code'];
}
foreach (array_diff($ex, $actual) as $priv) {
//if it doesn't match, insert
$sql = "INSERT INTO users_access_codes (uaID,user_id,access_code) VALUES (NULL,'".$user_id."','$priv')";
mysql_query($sql);
}
}
}
Btw, you could consider using INSERT IGNORE INTO
because of race conditions, but because you're not checking the statement return value, it won't matter here :)