Two conditions in foreach

foreach(($no_items as $key=>$txt ) && ($b_cost as $key=>$txt1 )) { $sql1 = "INSERT INTO bulk_s (`no_items`,`b_cost`) VALUES ('$txt[$key]','$txt1[$key]') "; } 

I have two dynamically created arrays on my php page whose values ​​I need to store in the database on the same line

my js code

  function changeIt() { my_div.innerHTML = my_div.innerHTML +"<br> items <input type='text' name='txt[]'+ i>" my_div.innerHTML = my_div.innerHTML +" cost <input type='text' name='txt1[]'+ j>" i++; j++; } 
+4
source share
2 answers

The foreach syntax is invalid for PHP. If you want to iterate over two arrays with the same keys at the same time, you need to iterate over the keys instead:

 foreach (array_keys($no_items) as $key) { $txt = $no_items[$key]; $txt1 = $b_cost[$key]; $sql1 = "INSERT INTO bulk_s …"; } 

However, note that you should never create SQL statements like this , so they are responsible for SQL injection . This is an unacceptable coding practice. In the best case, this makes your program less elegant, in the worst case, it opens the door for you, and there is a very simple, excellent solution .

+3
source

try it

  $i = 0; foreach($no_items as $key=>$items) { $data[$i] = array( 'variable1' => $items['no_items'], 'variable2' => $items['b_cost'], ); $sql1 = "INSERT INTO bulk_s (`no_items`,`b_cost`) VALUES ('$data['variable1']','$data['variable2']') "; $i++; } 
0
source

All Articles