Vahid Najafi
Vahid Najafi

Reputation: 5263

php: Use different arrays in foreach loop

I have 3 input that can be added dynamically. So the name of input is array, like:

<input type="text" name="qty1[]">
<input type="text" name="qty2[]">
<input type="text" name="qty3[]">

(Each of these input texts can be generated by javascript)

In my php file, I get them and want to insert to database (my controller in codeigniter):

$address = $this->input->post("qty1");
$LocX =    $this->input->post("qty2");
$LocY =    $this->input->post("qty3");

In my db part, where I want to use foreach and add to database:

Edit

foreach ($address as $key) {
  // I want to add $LocX and $LocY to the table
  // LocX and LocY are column names.
  $query = $this->db->query("INSERT INTO address (Comp_ID, Value, LocX, LocY)
                             VALUES(?, ?)", array($Comp_ID, $key ,? ,?));
}

I want to add all of them into foreach as parameter. As I searched it's not possible. What shoud I do? Thanks.

Edit2

The result of arrays, for example for $LocX :

Array
(
  [0] => test1
  [1] => test2
  [2] => test3
)

Upvotes: 0

Views: 102

Answers (3)

viral
viral

Reputation: 3743

I will suggest you to use Codeigniter syntax, and this will make your insert work,

foreach($address as $k => $v)
{
    $insert = array(
                'Comp_ID' => $Comp_ID,
                'Value' => $v,
            ); // insert array

    if(in_array($LocX[$k], $LocX)) // existance check
        $insert = array_merge($insert, array('LocX' => $LocX[$k]));

    if(in_array($LocY[$k], $LocY)) // existance check
        $insert = array_merge($insert, array('LocY' => $LocY[$k]));

    $this->db->insert('address', $insert); // No need to write full query
}

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

You can also use a for loop for this.

$address = $this->input->post("qty1");
$LocX =    $this->input->post("qty2");
$LocY =    $this->input->post("qty3");

$n=count($address);
for($i=0;$i<$n;$i++){
       $a=$address[$i];
       $x=$locX[$i];
       $y=$locY[$i];
       //insert here
}

Upvotes: 1

Tom V.
Tom V.

Reputation: 323

You can use the index in the foreach to get to the other elements. But you need to carefully check if the index value exists in the other arrays (isset check)

For example:

foreach ($address as $key => $value) {
  if(isset($LocX[$key], $LocY[$key]) {
      $a_LocX = $LocX[$key]; // This will be the locx of the address
      $a_LocY = $LocY[$key]; // This will be the locy of the address

      // Change your query to fit the table and fill in the locx and y.
      $query = $this->db->query("INSERT INTO address (Comp_ID, Value)
                             VALUES(?, ?)", array($Comp_ID, $key));
}

Upvotes: 1

Related Questions