多个SQL插入(插入次数取决于用户输入的数量)

时间:2015-07-22 18:17:17

标签: php mysql

我的网站上有一个模块,允许管理员将一些用户添加到组中。

这样的构建(使用选择框),您可以选择多个用户,但只能选择一个组:

Users:                       Group:
- user 1                     - group 1
- user 2                     - group 2
- user 3
- user 4
- user 5

在PHP内部,它看起来像这样:

$user_id = $_POST["user_id"]; //this can be an array
$group_id = $_POST["group_id"];

if (count($user_id) == 1) { 
    $sql = "INSERT IGNORE INTO users_groups (user_id, group_id) VALUES ($user_id[0],$group_id)"; 
} elseif (count($user_id) == 2) {
    $sql = "INSERT IGNORE INTO 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 INTO 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 INTO 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 INTO 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: Too many users selected';
    exit;
}

如何在更短的代码中获得此功能?也许是准备好的陈述,因为输入来自用户。

1 个答案:

答案 0 :(得分:0)

你在找这样的东西吗?

if(count($user_id)>5){
    echo 'Error: Too many users selected';
    exit;
}
$sql = "INSERT IGNORE INTO users_groups (user_id, group_id) VALUES ($user_id[0],$group_id)";
for ( $i = 1; $i < count($user_id); $i++) {
    $sql .= ", ($user_id[$i],$group_id)"
}