php - Multiple SQL inserts (number of inserts depending on number of user input) -
i have module on website allows admin add users group.
it build (with selectboxes), can select multiple users 1 group:
users: group: - user 1 - group 1 - user 2 - group 2 - user 3 - user 4 - user 5
inside php, looks this:
$user_id = $_post["user_id"]; //this can array $group_id = $_post["group_id"]; if (count($user_id) == 1) { $sql = "insert ignore users_groups (user_id, group_id) values ($user_id[0],$group_id)"; } elseif (count($user_id) == 2) { $sql = "insert ignore users_groups (user_id, group_id) values ($user_id[0],$group_id), ($user_id[1],$group_id)"; } elseif (count($user_id) == 3) { $sql = "insert ignore users_groups (user_id, group_id) values ($user_id[0],$group_id), ($user_id[1],$group_id), ($user_id[2],$group_id)"; } elseif (count($user_id) == 4) { $sql = "insert ignore users_groups (user_id, group_id) values ($user_id[0],$group_id), ($user_id[1],$group_id), ($user_id[2],$group_id), ($user_id[3],$group_id)"; } elseif (count($user_id) == 5) { $sql = "insert ignore users_groups (user_id, group_id) values ($user_id[0],$group_id), ($user_id[1],$group_id), ($user_id[2],$group_id), ($user_id[3],$group_id), ($user_id[4],$group_id)"; } else { echo'error: many users selected'; exit; }
how can in shorter code? maybe prepared statements because inputs users.
are looking this?
if(count($user_id)>5){ echo 'error: many users selected'; exit; } $sql = "insert ignore users_groups (user_id, group_id) values ($user_id[0],$group_id)"; ( $i = 1; $i < count($user_id); $i++) { $sql .= ", ($user_id[$i],$group_id)" }
Comments
Post a Comment