-2

Herein, I am doing this and instead of getting the MAX value for CustomerID, i am getting 0.

My CustomerData Table :

     Columns

    1   CustomerID      
    2   Name         
    3   PhoneNumber 
    4   Address      

My OrderTable1 Table

 Columns

1   OrderID    
2   TableID 
3   OrderDate   
4   OrderStatus
5   OrderDesc   
6   CustomerID

INSERT INTO OrderTable1 (OrderDate,OrderStatus,OrderDesc,CustomerID)
VALUES ('$LenthOfService','$Quantity','$ItemName','(SELECT MAX(CustomerID) FROM CustomerData)');
Dharman
  • 30,962
  • 25
  • 85
  • 135
Manu Kaur
  • 1
  • 1

1 Answers1

0

You can use the INSERT INTO .. SELECT statement. For the input variable values, we can SELECT them alongside maximum value of CustomerID from the CustomerData table:

INSERT INTO OrderTable1 (OrderDate,OrderStatus,OrderDesc,CustomerID)
SELECT MAX('$LenthOfService') AS OrderDate,
       MAX('$Quantity') AS OrderStatus,
       MAX('$ItemName') AS OrderDesc,
        MAX(CustomerID) AS CustomerID
FROM CustomerData

In order to be ANSI SQL compliant, we will need to use Max() function around the variable values. More details at: SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Also, it seems that you are not using Parametrized queries. In that case, your code will be vulnerable to SQL injection related attacks. Please learn to use Prepared Statements

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
  • *"Even [`real_escape_string`](https://stackoverflow.com/a/12118602/2469308) cannot secure it completely."* - That reference is for the mysql_* api, not for the mysqli_* api; totally different animal here. – Funk Forty Niner Nov 19 '18 at 04:15
  • $LenthOfService and $quantity and $ItemName, i am getting from user input through android app and these fields are not in CustomerData – Manu Kaur Nov 19 '18 at 04:20
  • @ManuKaur yeah that is why they will be used as string literals in this query. try it once – Madhur Bhaiya Nov 19 '18 at 04:49
  • I tried now it only works for CustomerID. I have edited my question – Manu Kaur Nov 19 '18 at 05:11