【问题标题】:Foreach of TWO Looping TextFields, possible?Foreach 两个循环文本字段,可能吗?
【发布时间】:2011-11-10 08:27:05
【问题描述】:
    /* 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++;
 });

在上面的代码中,它增加了两个字段:experience 和 years 文本字段

    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(); }
}

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

我需要一个答案:D

【问题讨论】:

    标签: php mysql arrays foreach nested-loops


    【解决方案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]));
    }
    

    【讨论】:

    • 抱歉复制并粘贴了第二个代码,但出现错误:Fatal error: Call to a member function prepare() on a non-object in $stmt = $dbh-&gt;prepare("INSERT INTO experiences (number, experience, years) VALUES (?, ?, ?)");。嗯,我会怎么做?我,这里不是很好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 2016-06-11
    相关资源
    最近更新 更多