javascript - 使用 foreach 进行循环插入

标签 javascript php html

我想插入多行数据库表。

HTML:

<tr>
<td style="display:none"><input type="text" rows="4" name="teste[]" value="<?php echo $produto8["Id"]; ?>"></td>
<td><textarea rows="4" name="Notas[]" value="<?php echo $produto8["Notas"]; ?>"></textarea></td>
<td><select class="form-control" name="EstadoFinal[]"><?php echo $produto8["EstadoFinal"]; ?><option value=<?php echo $ln['Id']; ?>><?php echo $ln['Estado']; ?></option>
<?php        
$sql = "SELECT * FROM raddb.Status WHERE Id IN ('8') ORDER BY Estado ASC";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['Id'].'">'.$ln['Estado'].'</option>';
}
?>      
</select></td> 
</tr> 

数据提交:

function inserir_registo8()
{  

    var dadosajax = {
     'Id' : $("input[name^='teste']").val(),
     'Notas' : $("textarea[name^='Notas']").val(),
     'EstadoFinal' : $("select[name^='EstadoFinal']").val()
    };
    console.log(dadosajax);
    $.ajax({
        url: './resolucaooratorio',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){
          $(".error_message").removeClass('hide');
        },
        success: function(result)
        { 
        console.log(result);
         $("#spoiler8").load(" #spoiler8 > *");
        }       
    });

}

PHP:

$Id = mysqli_real_escape_string($conn, $_POST["Id"]);      
$Notas = mysqli_real_escape_string($conn, $_POST["Notas"]);
$EstadoFinal = mysqli_real_escape_string($conn, $_POST["EstadoFinal"]);
$Colaborador1 = $_SESSION['usuarioId'];   
foreach($Id as $value) {                  

    $query = 'UPDATE RegistoOratorio SET Notas= ?, EstadoFinal= ?, Colaborador1= ? WHERE Id = ? '; // ou WHERE id = ?
    $stmt = $conn->prepare( $query );
    $stmt->bind_param("ssss", $Notas[$value], $EstadoFinal[$value], $Colaborador1[$value], $value ); // ou ("si", $hash, $idUsuario)
    $stmt->execute();   

 }  

但是您没有插入,因为您没有收到 html 值。

我做console.log (dataajax);返回这个,但不返回数组:

{Id: "11", Notas: "", EstadoFinal: "8"}

但是你应该返回这个:

{Id: "8", Notas: "", EstadoFinal: "8"} {Id: "9", Notas: "", EstadoFinal: "8"} {Id: "10", Notas: "", EstadoFinal: "8"} {Id: "11", Notas: "", EstadoFinal: "8"}

print_r($_POST);返回:

Array
(
    [Id] => Array
        (
            [0] => 11
            [1] => 10
            [2] => 12
            [3] => 9
            [4] => 2
            [5] => 4
            [6] => 1
            [7] => 3
            [8] => 7
            [9] => 6
            [10] => 8
            [11] => 5
        )

    [Notas] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => 
            [5] => 
            [6] => 
            [7] => 
            [8] => 
            [9] => 
            [10] => 
            [11] => 
        )

    [EstadoFinal] => Array
        (
            [0] => 8
            [1] => 8
            [2] => 8
            [3] => 8
            [4] => 
            [5] => 
            [6] => 
            [7] => 
            [8] => 
            [9] => 
            [10] => 
            [11] => 
        )

)

最佳答案

您需要获取每一行的每个元素的值。这样你只能得到第一个值。也许这会起作用,未经测试:

function inserir_registo8()
{  
    var Ids = [];
    $("input[name^='teste']").each(function() {Ids.push(this.value)});

    var Notass = [];
    $("textarea[name^='Notas']").each(function() {Notass.push($(this).val())});

    var EstadoFinals = [];
    $("select[name^='EstadoFinal']").each(function() {EstadoFinals.push($(this).val())});

    var dadosajax = {
     'Id[]' : Ids,
     'Notas[]' : Notass,
     'EstadoFinal[]' : EstadoFinals
    };
    console.log(dadosajax);
    $.ajax({
        url: './resolucaooratorio',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){
          $(".error_message").removeClass('hide');
        },
        success: function(result)
        { 
        console.log(result);
         $("#spoiler8").load(" #spoiler8 > *");
        }       
    });

}

如果您使用 print_r($_POST); 向我展示 $POST 中的内容,我也可以在 PHP 方面提供帮助。

您可以通过使用索引迭代所有数组来处理 $_POST 中的数组:

$Ids = $_POST["Id"];      
$Notass = $_POST["Notas"];
$EstadoFinals = $_POST["EstadoFinal"];
$Colaborador1 = $_SESSION['usuarioId'];   
$count = count($Ids);
for($i = 0; $i<$count; ++$i) {                  
    $value = $Ids[$i];
    $Notas = $Notass[$i];
    $EstadoFinal = $EstadoFinals[$i];
    if(!empty($EstadoFinal)) {
        $query = 'UPDATE RegistoOratorio SET Notas= ?, EstadoFinal= ?, Colaborador1= ? WHERE Id = ? '; // ou WHERE id = ?
        $stmt = $conn->prepare( $query );
        $stmt->bind_param("ssss", $Notas, $EstadoFinal, $Colaborador1, $value ); // ou ("si", $hash, $idUsuario)
        $stmt->execute();   
    }
} 

我添加了一个检查 estadoFinal 是否为空。在 PHP 中添加比在 javascript 代码中添加更容易。

关于javascript - 使用 foreach 进行循环插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57178907/

相关文章:

javascript - angularJs - 不同结构的两种不同模型是否可以同步或共享状态?

javascript - 如何使用 javascript 在 jquery 选项卡内重定向?

javascript - 当输入通过管道传输时,Babel CLI 会忽略配置

Javascript 通过标签 ID 跟踪页面中的标签总数 (<div>)

javascript - 单选按钮值添加到数组?

html - 使用 CSS 从底部到顶部 float div?

html - 具有渐变的响应式宽度 css 三 Angular 形

javascript - 如何让以下代码等待 api 调用准备好后再恢复?

php - codeigniter加载一个没有任何html标题的 View 进行打印

javascript - Ajax 调用不起作用?