Insert array post php mysql

0

Good day forum.

I have a form where I send call two input number where its name property called an array <input type='number' class='form-control' name='cantidad[]' id='cantidad[]' value='"+cantidad+"' taking into account that the array can bring more than 2 elements, like the grego to a database (table) by means of the method post.

This is my form. In the id details, my quantity number entries are appended from js and the data is shown on the label.

        <form method="POST" id="formulario" name="formulario">  
                        <div class="form-group col-lg-2 col-md-2 col-ms-2 col-xs-12">
                            <label>Peso:</label>
                            <input type="text" name="peso" id="peso" class="form-control" value="<?php echo $inputs->peso; ?>">
                        </div>

                        <div class="form-group col-lg-2 col-md-2 col-ms-2 col-xs-12">
                            <label>Tarimas:</label>
                            <input type="text" name="tarimas" id="tarimas" class="form-control" value="<?php echo $inputs->tarimas; ?>">
                        </div>


                        <div class="form-group col-lg-3 col-md-3 col-sm-6 col-xs-12">
                            <a data-toggle="modal" href="#myModal">
                                <button id="btnAgregarArt" type="button" class="btn btn-primary" onclick="mostrar()"><span class="fa fa-plus"></span> Agregar Productos</button>
                            </a>
                        </div>
                        <div id="resultados"></div>
                        <div class="col-lg-10 col-ms-10 col-md-10 col-xs-12">
                            <table id="detalles" class="table table-striped table-bordered table-condensed table-hover">
                                <thead style="background-color: #A9D0F5" >
                                    <th class="text-center">Opciones</th>
                                    <th class="text-center">Modelo</th>
                                    <th class="text-center">Piezas</th>

                                    <th colspan="2" class="text-center">Verificado</th>
                                    <th class="text-center">Actualizar Conteo</th>
                                </thead>
                                <tfoot>
                                    <th>Total</th>
                                    <th></th>
                                    <th><h4 id="total"></h4><input type="hidden" name="total_piezas" id="total_piezas"></th>
                                </tfoot>

                                <tbody>


                                </tbody>

                            </table>
                        </div>

                        <div class="form-group col-lg-12 col-md-12 col-ms-12 col-xs-12" id="guardar">
                            <button class="btn btn-primary" type="submit" id="btnGuardar"><i class="fa fa-save"></i> Guardar</button>
                            <button class="btn btn-danger" type="button" onclick="cancelarForm()"><i class="fa fa-arrow-left"  id="btnCancelar"> </i> Cancelar </button>
                        </div>
                </form>

This is my js where I send my number [], using a function

function agregarDetalle(idProducto,modelo){

var  cantidad = 1;
var teorico = 1;
if(idProducto != ""){


    var fila ="<tr class='filas' id='fila" + cont +"'>" +
                 "<td><button type='button' class='btn btn-danger' onclick='eliminarDetalle("+cont+")'>x</button></td>" +
                 "<td><input type='text' name='idProducto[]' value='"+idProducto+"'>"+modelo+"</td>" +
                 "<td><input type='number' class='form-control' name='cantidad[]' id='cantidad[]' value='"+cantidad+"'></td>" +
                 "<td><input type='hidden' class='form-control' name='c' id='c' value='"+teorico+"'></td>" +

             "</tr>";
             cont++;
             detalles = detalles + 1;
             $("#detalles").append(fila);
             modificarSubtotales();
             evaluar();


}else{

    alert("Error, al ingresar los datos del productos, favor de revisar producto");
}

}

In the image is where I add my items of the pieces that I will be adding and they can be more than two models and each model their pieces, the point is to register that number of pieces by the post method.

This is my ajax request.

$("#formulario").submit(function(event){
$("#btnGuardar").attr("disabled",true);

var parametros = $(this).serialize();

$.ajax({
    type: "POST",
    url:"index.php?action=addIngresos",
    data: parametros,
    beforeSend:function(objeto){
        $("#resultados").html("Mensaje:Cargando...");
    },
    success: function(datos){
        $("#resultados").html(datos).fadeIn();
        $("#resultados").html(datos);
        $("#btnGuardar").attr("disabled", false);
    }
});
event.preventDefault();

})

This my php of income, all the command to call from my form by the method post.

<?php 
if(count($_POST) > 0){
    $ing = new CountData();
    $ing->ubicacion = $_POST["ubicacion"];
    $ing->producto_id = $_POST["idProducto"];
    $ing->folio_id = $_POST["idIngreso"];
    $ing->piezas = $_POST["cantidad"];
    $ing->process_id = $_POST["indI"];
    $ing->add();

}
print "<script>alert('Ingreso registrado satisfactoriamente');</script>";

? >

Executing, I get this error:

Notice: Array to string conversion in C:\xampp\htdocs\solicitud\core\app\model\CountData.php on line 17

Where my arrangement is not taking me well or I'm doing it wrong. This is my add (add) function and whoever has data from the array is pieces that is my line 17. Someone knows how I can pass the data and insert them

public function add()
    {
        $sql = " insert into ".self::$tablename. " (ubicacion,producto_id,folio_id,piezas,process_id)";
        $sql .= " value (\"$this->ubicacion\",$this->producto_id,$this->folio_id,$this->piezas,$this->process_id)";
        return Executor::doit($sql);
    }
    
asked by Ever 17.01.2018 в 17:02
source

3 answers

0

I found this option to what I wanted, I thank you, greetings.

    $num_elementos = 0;
     $num = 0;


     while($num_elementos < count($total_folios) && $num < count($total_cantidad))
     {
        $ing->producto_id = $total_folios[$num_elementos];
        $num_elementos=$num_elementos + 1;
        $ing->piezas = $total_cantidad[$num];
        $num=$num+1;
        $ing->add();
     }
    
answered by 18.01.2018 / 18:12
source
0

When you have inputs named to be arrays, what you get are arrays in your $ _POST variable.

So, the problem is that you are trying to save arrays in the fields of your string or int type table and therefore, it shows you that warning.

To correctly save each information in a record, you will have to go through the arrays with a cycle and make the insert.

Or you could convert your arrays into a string. EYE : It all depends on how you are going to save your data.

<?php
 $array = array('apellido', 'email', 'teléfono');
 $separado_por_comas = implode(",", $array);

 echo $separado_por_comas; // apellido,email,teléfono
?>

Replicate NOTICE

Open phptester.net and add

<?php
    $stuff = array(1,2,3);
    print $stuff;  //PHP Notice:  Array to string conversion in yourfile on line 3
?>

You will see the error that appears to you and what I am talking about.

    
answered by 17.01.2018 в 23:54
0

The problem is that the $ _POST ['amount'] contains an array, you are trying to insert the entire array into a single field which you can not do, what you are doing, what you should do in your php is to convert the $ _POST ['quantity'] array into a single string so you can insert it in the field of your table. In this way you convert the arrangement into a string:

<?php
$cantidad = implode('/', $POST['cantidad']);
?>

If you print this it gives you a single string that contains all the values separated by a "/", something like "value1 / value2 / value3", and this string you could insert into a table field that should be " Varchar "or" Text ". If you later want to access those values by bringing the string of your database you could do it, suppose that the string you brought from your database was stored in the variable $ sumaStr, then:

<?php
  $cantidadArray = explode('/', $cantidadStr);
?>

This would return an array like $ AmountArray = ["value1", "value2", "value3"];

    
answered by 18.01.2018 в 21:17