0

**My Aim:**Insert the Qty into Db of each I_Code as per each I_Name.

Expected Output

      stock_color
I_Code   I_Qty   I_Name
M1        50      PYC
M2        50      PYC
M1        25      P285C
M3        70      P285C
M4        15      P285C

PHP+Mysql

$ink={M1,M2,M1,M3,M4};
$Qty={50,50,25,70,15};
$ink_name={PYC,P285C};

for($j=0;$j<count($ink_name);$j++)
{
         $sql[] = "insert into stock_color (I_Code,I_Qty,I_Name) values ('$ink[$j]','$Qty[$j]','$ink_name[$j]')"
                foreach ($sql as $query) {
                         mysqli_query($query,$con);
                     }          
}

Now,Code is working but with wrong results.Please help me out.Thanks in advance

6
  • 3
    You need to swap the parameters in your mysqli_query. And the foreach-loop should not be inside the for-loop.
    – MrDarkLynx
    Feb 23, 2017 at 8:01
  • 1
    In general, never execute a query inside a loop. However, when using parametrised queries in pdo (which is what you should be doing) the opposite is true!
    – Strawberry
    Feb 23, 2017 at 8:03
  • Should be mysqli_query($con,$query);
    – Akshay
    Feb 23, 2017 at 8:04
  • @Strawberry I wan't aware of Parametrised queries in pdo, I will look into that.
    – Babaji
    Feb 23, 2017 at 8:09
  • @Akshay Its, mysqli_query($query,$con), because for mysqli_query($con,$query); its giving error.
    – Babaji
    Feb 23, 2017 at 8:12

1 Answer 1

0

please try this code

<?php
 $ink=array('M1','M2','M1','M3','M4');
 $Qty=array(50,50,25,70,15);
 $ink_name=array('PYC','PYC','P285C','P285C','P285C');

 for($j=0;$j<count($ink_name);$j++)
  {
     //$sql .= "insert into stock_color (I_Code,I_Qty,I_Name) values ('$ink[$j]','$Qty[$j]','$ink_name[$j]')";
    if($j==0){
        $sql .= " ('$ink[$j]','$Qty[$j]','$ink_name[$j]')";
    } else {
        $sql .= ", ('$ink[$j]','$Qty[$j]','$ink_name[$j]')";
    }

   }
   echo $final_query = "insert into stock_color (I_Code,I_Qty,I_Name) values " .$sql;
?>
2
  • But, there might be so many entries, I can't write manually for each one.
    – Babaji
    Feb 23, 2017 at 8:18
  • in this case need to other solution . ok try to give solution Feb 23, 2017 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.