两个循环TextField的Foreach,可能吗?

时间:2011-09-05 03:54:20

标签: php mysql arrays foreach nested-loops

    /* Adding Experiences */
$("#addExperience").click(function () {

if(experiencectr>5){
        alert("WOW! But 5 experiences are enough.");
        return false;
}   

var newTextBoxDiv = $(document.createElement('div'))
     .attr("id", 'ExperienceDiv' + experiencectr);

newTextBoxDiv.html('<label>Experience No. '+ experiencectr + ' : </label>' +
      '<input type="text" name="experience[]" id="experience' + experiencectr + '" >&nbsp;' +
      '<input type="text" id="year' + experiencectr +
      '" size="5" name="years[]"><label>years</label>');

newTextBoxDiv.appendTo("#ExperienceBoxesGroup");


experiencectr++;
 });

在上面的代码中,它添加了两个字段:经验和年份文本字段

    foreach ($_POST['experience'] as $experience) {
// save $experience to database
$sql_experience = "INSERT INTO experiences(number,experience)
values ('$number','$experience')";
if($result3 = mysql_query($sql_experience ,$db))
    {
            foreach ($_POST['years'] as $years) {
            $sql_years = "UPDATE experiences SET years=$years WHERE experience=$experience";
            if($result = mysql_query($sql_years ,$db))
                { }
            else 
                { echo "ERROR: ".mysql_error(); }
            }
    }
else 
    { echo "ERROR: ".mysql_error(); }
}

在上面的代码中,它保存到数据库中,但字段列在所有行中都具有SAME值。你能帮帮我吗?

我需要一个答案:D

1 个答案:

答案 0 :(得分:1)

您必须获取索引才能访问其他数组中的值:

foreach($_POST['experiences'] as $idx => $experience) {
    $sql = "INSERT INTO experiences (number, experience, years)
            VALUES ({$idx}, {$experience}, {$_POST['years'][$idx]}");
    // execute query, etc
}

这会有效,但您可能不应该这样做,因为它让您对SQL injections开放。更好的方法是清理输入(例如:mysql_reaL_escape_string或其mysqli等价物)

最好的方法是using prepared statements

$stmt = $dbh->prepare("INSERT INTO experiences (number, experience, years) 
                       VALUES (?, ?, ?)");

foreach($_POST['experiences'] as $idx => $experience) {
    // pass values and execute
    $stmt->execute(array($idx, $experience, $_POST['years'][$idx]));
}