0

I'm using a php variables in mysql,but getting error while trying to add the php variables in a field and insert. Here is my sql query:

INSERT INTO my_table (quantity,price) VALUES(quantity+$value,1000) WHERE id=$id;

thanks in advance.

6
  • Sounds like you want to update a row instead of inserting it? Commented May 2, 2019 at 5:52
  • 2
    What is the db error? Commented May 2, 2019 at 5:53
  • nope i've timestamps too that i can store each individual insertion. Commented May 2, 2019 at 5:54
  • So you don't want to update a row? You want to insert a new row then? Your question is rather unclear, we can't read your mind or see what your goal here is unless you explicitly tell us. Commented May 2, 2019 at 5:58
  • ok sorry if i was not clear enough in the question, and yes i did not want to update the row. i want to insert each time. Commented May 2, 2019 at 6:04

3 Answers 3

1

You can not insert rows with WHERE or by adding values (like you attempt with quantity+$value), as there are no values until after the insert has completed.

If you want to update an existing row,

UPDATE my_table 
SET quantity = quantity + $value,
    price = 1000
WHERE id = $id

Or if you want to insert a row,

INSERT INTO my_table (id, quantity, price) 
VALUES ($id, $value, 1000)

Keep in mind that these queries are insecure, as they are not using prepared statements with placeholders.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer Qirel. just want to know how can i insert new row for specific product id then? my case is like whenever the customer buys a product i want to store the purchase record with timestamp.
Create a table with a primary key (probably some arbitrary ID), the customer ID (or any other unique customer-identifier), a timestamp (just use the CURRENT_TIMESTAMP default value) and the amount.
0

I think you are trying to update your query

UPDATE my_table 
  SET quantity = quantity + $value, price= 1000
  WHERE id = $id

3 Comments

i'm not and now i know i cant use the WHERE clause in an INSERT query, i need to insert each time not update as i want to track the insertions based on timestamps later. thanks.
INSERT into mytable (logins) SELECT max(logins) + 1 FROM mytable
you can use sub query similar to above query
0

you cannot insert row using the "WHERE".

for insert you can use:

INSERT INTO my_table (id, quantity, price) VALUES ($id, $value, 1000);

for update you can use:

UPDATE my_table 
   SET quantity = quantity + $value,
       price = 1000
   WHERE id = $id;

for reference you can see:

https://www.w3schools.com/sql/sql_insert.asp
https://www.w3schools.com/sql/sql_update.asp

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.