How to insert an html input array into mysql using PDO

后端 未结 1 1858
北荒
北荒 2021-01-29 06:23

I have an HTML form that has 2 dynamic fields which are:

相关标签:
1条回答
  • 2021-01-29 06:44

    Assuming the table's name shown in the image you posted in your question ingredient_quantity in your database, and you said you already have the recipe-ID PHP Fiddle

    <?php 
        $newid = 'A10';
        //considering this is your table shown in the picture
        $sql = "INSERT INTO ingredient_quantity VALUES";
    
        for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
            $sql .= " (:newid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),"; 
        }
    
        // remove the last (,) from the $sql
        $sql = rtrim($sql, ',');
        $sth = $con->prepare($sql);
    
        // binding parameters 
        for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
            $varIng = $_POST['ingredients'][$i];
            $varQnty = $_POST['quantity'][$i];
            $sth->bindParam(':newid' .$i , $newid , PDO::PARAM_STR);
            $sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
            $sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
        }
        $sth->execute();
    ?>
    

    EDIT 1:

    for the above code I have an error as the ingredients[] array starts from 0 and not 1, the final index of the for loop will be undefined, so work around it make the last for loop like the following:

    for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
            $varIng = $_POST['ingredients'][$i];
            $varQnty = $_POST['quantity'][$i];
            $j = $i + 1;
            $sth->bindParam(':newid' .$j , $newid , PDO::PARAM_STR);
            $sth->bindParam(':ingredient' .$j , $varIng , PDO::PARAM_STR);
            $sth->bindParam(':quantity' .$j , $varQnty , PDO::PARAM_STR);
        }
    

    EDIT 2: You may try doing it with ? placeholders instead of named placeholders like this PHP Fiddle 2:

    //considering this is your table shown in the picture
        $sql = "INSERT INTO ingredient_quantity VALUES";
    
        for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
            $sql .= " ( ? , ? , ? ) , "; 
        }
    
        // remove the last (,) from the $sql
        $sql = rtrim($sql, ',');
        $sth = $con->prepare($sql);
    
        // binding parameters 
        $j = 1;
        for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
            $varIng = $_POST['ingredients'][$i];
            $varQnty = $_POST['quantity'][$i];
            $sth->bindValue( $j , $varIng);
            $sth->bindValue( $j + 1, $newid);
            $sth->bindValue( $j + 2, $varQnty);
            $j += 3;
        }
        $sth->execute();
    
    0 讨论(0)
提交回复
热议问题