AndroidBoy AndroidBoy - 5 months ago 10
PHP Question

Why This PHP code Not inserting proper ways

Here we go, when i try to Insert my First Query Running and Data Inserted but my Second Query not Working.At the same Time to comment the first Query Second one working good. while both means I am stuck

if($order_no!="" && $cus_name!="")
{
//fs_code: set primary key into auto means use this qry before inserting
$query1 = "SET IDENTITY_INSERT order_creation ON";
$stmt1 = sqlsrv_query($conn, $query1);

$sql = "INSERT INTO order_creation (order_no,cus_name,cus_id,types,created_date,Status,id) VALUES('$order_no','$cus_name','$cus_id','$type',FORMAT(CURRENT_TIMESTAMP,'M/d/yyyy h:mm:sstt'),'$Status','$fmax')";

if(sqlsrv_query($conn,$sql))
{
echo 'success-1';
}
else
{
echo 'failure-1';
}
}
for($i=0;$i<count($goods_name);$i++)
{
if($goods_name[$i]!="")
{
$sql = "INSERT INTO order_Goods (order_no,goods_name,goods_qty,date,created_date,Balance_Qty,Supply_Qty,ProductPrice,id) VALUES('$order_no','$goods_name[$i]','$goods_qty[$i]',FORMAT(CURRENT_TIMESTAMP,'d/MM/yy h:mm:sstt'),'$created_date[$i]','$goods_qty[$i]','$Supply_Qty','$ProductPrice[$i]','$get_maxres')";

if(sqlsrv_query($conn,$sql))
{
echo 'success-2';
}
else
{
echo 'failure-2';
}
$get_maxres++;
}
}

sqlsrv_close($conn);

Answer

You're not using the correct syntax to substitute an array value into a string. When the array index contains a variable, you need to use the "complex" syntax, where the array variable is surrounded by {}.

$sql = "INSERT INTO order_Goods (order_no,goods_name,goods_qty,date,created_date,Balance_Qty,Supply_Qty,ProductPrice,id)
     VALUES('$order_no','{$goods_name[$i]}','{$goods_qty[$i]}',FORMAT(CURRENT_TIMESTAMP,'d/MM/yy h:mm:sstt'),'{$created_date[$i]}','{$goods_qty[$i]}','$Supply_Qty','{$ProductPrice[$i]}','$get_maxres')";

See the section Variable parsing in the PHP Strings documentation.

You also need to enable IDENTITY_INSERT on the second table. Put this before the for loop:

sqlsrv_query($conn, "SET IDENTITY_INSERT order_creation OFF");
sqlsrv_query($conn, "SET IDENTITY_INSERT order_Goods ON");