milon hossain
milon hossain

Reputation: 19

How to add and insert values in mysql

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.

Upvotes: 0

Views: 76

Answers (3)

SM Imtiaz Hussain
SM Imtiaz Hussain

Reputation: 447

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

Upvotes: 0

Sarfaraz
Sarfaraz

Reputation: 146

I think you are trying to update your query

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

Upvotes: 0

Qirel
Qirel

Reputation: 26450

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.

Upvotes: 1

Related Questions