如何使用自己的类型插入多个数据?

时间:2009-12-27 17:02:17

标签: php mysql

<input name="names[]" type="text"/><select><option value="male">male</option><option value="female">female</option></select>  
<input name="names[]" type="text"/><select><option value="male">male</option><option value="female">female</option></select>  
<input name="names[]" type="text"/><select><option value="male">male</option><option value="female">female</option></select>  





    if (!empty($_POST['names'])) {
    foreach ($_POST['names'] AS $names) {
        // add to the database
        if (!empty($names)){
            $rs=mysql_query("SELECT names FROM table WHERE names = '$names' LIMIT 1");
            if(mysql_num_rows($rs) == 0) {
        mysql_query("INSERT INTO table (names,gender) VALUES ('$names','$gender')");
            }
        }
    }
}

这确实插入了名字,但我不知道如何让性别为每个名字起作用。

1 个答案:

答案 0 :(得分:1)

您需要为SELECT元素命名:

<input name="names[]" type="text"/><select name="genders[]"><option value="male">male</option><option value="female">female</option></select>

现在,您可以使用$_POST['names']的密钥来获取相应的性别:

foreach ($_POST['names'] AS $key => $names) {
    // add to the database
    if (trim($names) != '' && !empty($_POST['genders'][$key]) && in_array($_POST['genders'][$key], array('male', 'female'))) {
        $gender = $_POST['genders'][$key];
        $rs = mysql_query("SELECT names FROM table WHERE names = '".mysql_real_escape_string($names).' LIMIT 1");
        if (mysql_num_rows($rs) == 0) {
            mysql_query("INSERT INTO table (names,gender) VALUES ('".mysql_real_escape_string($names)."','$gender')");
        }
    }
}

您还应该使用mysql_real_escape_string对用户发送的数据进行整理。