PHP array returning the same value

Question!

I'm stuck on this and I'm not actually seeing where exactly the problem is.

I have a bunch of input tags which are placed like that:

<div class="col-md-3">
    <label>Material 1</label>
    <input hidden="hidden" name="idMaterial[]" value="13" type="text" />
    <input class="form-control" name="total[]" type="text" />
</div>

<div class="col-md-3">
    <label>Material 2</label>
    <input hidden="hidden" name="idMaterial[]" value="8" type="text" />
    <input class="form-control" name="total[]" type="text" />
</div>

I have 20 input like that, the idea here is that if I write 10 in the Material 1's input field, my DB would receice something like:

id         => A.I
idMaterial => 13
total      => 10

But once I run the code, it comes like that (repeating the idMaterial, even if I write in more than 1 input. It always repeat the first):

idMaterial: 13
total: 10

idMaterial: 13
total: 20

That's the code I'm using to receive that form:

$idMaterial = array();
$total  = array();

if($this->input->post('total')){
    foreach($this->input->post('idMaterial') as $row){
        $idMaterial = $row;

        foreach($this->input->post('total') as $row2){
            $total  = $row2;

            echo 'Material: '. $idMaterial .'<br> Total: '. $total. '<br><br>'; // TESTING THE OUTPUT
            $query = $this->pedido->salvaLabMaterial($total, $idMaterial); // I'M SENDING THE DATA TO MODEL HERE
        }
    }
}

Any tips is very welcome.

By : VerdenKaf


Answers

@RiggsFolly

That's where I'm sending the posts the way it comes from the HTML form as you said:

$query = $this->pedido->salvaLabMaterial($this->input->post('total'), 
                                         $this->input->post('idMaterial'), 
                                        );

The model:

public function salvaLabMaterial($this->input->post('idMaterial'), $this->input->post('total')){

    $query = $this->db->query(" insert into labpedidomaterial (idMaterial, total) values ('".$this->input->post('idMaterial')."', '".$this->input->post('total')."') ");

}
By : VerdenKaf


You could use Convert.ChangeType for that:

public void Add(object value)
{
    var t = Convert.ChangeType(value, typeof(T));
}

See the fiddle: https://dotnetfiddle.net/0Tfgyz



If you need object insead of T you can use dynamic in your Add method.

 public void Add(object value)
 {
      //When T is decimal, then I get 
      // System.InvalidCastException
      dynamic t1 = value;
      var t = (T)t1;
 }
By : steryd


This video can help you solving your question :)
By: admin