Search code examples
phpmysqlarrayssql-deletenotin

Delete when UserID = 1 and CourseID not in array?


This is the SQL code I am using:

For some reason it deletes all records for the UserID but does not take into account the NOT IN array. I need it to delete only if the user ID = the current user AND the courseID of that user is not in the array..

mysql_query("DELETE FROM tblLinkUserCourse WHERE ((UserID=$CurrentUserID) AND (CourseID NOT IN ({$new_array})))");

Solution

  • 1) Remove all unnecessary () from query.

    2) Check $new_array contains all your course_id or not and constructed as string. If not constructed as string and comma separated use this code.

    $new_array = implode(',', $new_array);
    mysql_query("DELETE FROM tblLinkUserCourse WHERE UserID=$CurrentUserID AND CourseID NOT IN ({$new_array})");