Foreach loop for inserting multiple rows

The client sends to the server an array with the services offered by a business and these must enter a db table…here is the foreach loop:

 foreach ($service as $value) {
    $stmt = $connection->prepare('INSERT into services_list (servicename) values (?)');
          $stmt->bind_param('s',$value);  
          $stmt->execute();
          $stmt->close();
                        }          
          }

And here is my problem,from the client comes also another array containing the prices of the services above and these must enter the db also but they must match their corresponding service…take a look at a table snapshot to see what I mean:
image

So…what I tried is a foreach loop inside another foreach loop:


 foreach ($service as $value) {
          $stmt = $connection->prepare('INSERT into services_list (servicename) values (?)');
          $stmt->bind_param('s',$value);  
          $stmt->execute();
          $stmt->close();
           foreach ($price as $euro){
          $stmt = $connection->prepare('INSERT into services_list (price) values (?)');
          $stmt->bind_param('s',$euro);  
          $stmt->execute();
          $stmt->close();   
                    }          
      }

it creates a mess in the table…what can I do to correctly match in the db table the services with the their prices?I hope you understand me…

$stmt = $connection->prepare('INSERT into services_list (servicename, price) values (?, ?)');
$stmt->bind_param('ss', $value, $price);  

foreach ($service as $item) {
    $value = $item['service'];
    $price = $item['price'];
    $stmt->execute();
}
$stmt->close();

That’s exactly the reason why I said that you should group service and price in the form together.

1 Like

hmmmm
So that it can be in the same array?
Now it makes sense…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.