Reputation: 199
Normally I insert data in MySql in one table (sales) example.
string query = "INSERT INTO sales (price, user, date) " +
"VALUES(" +
"'" + txtQuant.Text + "'," +
"'" + txtLog.Text + "'," +
"NOW())";
But now I change my mind and decided to separately create another table which will I name settings for column price. this is my first time to do this so I have no idea what to do.
I tried this.
string query = "INSERT INTO sales (user, date), settings (price) " +
"VALUES(" +
"'" + txtLog.Text + "'," +
"NOW())", "'" + txtQuant.Text + "'";
but it doesn't work.
Upvotes: 0
Views: 6534
Reputation: 173542
You have to separate the two queries:
INSERT INTO sales (user, date) VALUES ( ... )
Followed by
INSERT INTO settings (price) VALUES ( ... )
If sales
has an auto_increment
primary key, you can use LAST_INSERT_ID()
in the second query to reference sales.id
after the insertion.
INSERT INTO settings (sale_id, price) VALUES (LAST_INSERT_ID(), ... )
Note that correlated queries like these are best put inside a transaction.
Upvotes: 0
Reputation: 213
MySQL doesn't support inserting into multiple tables in a single query (see sql - insert into multiple tables in one query).
You can place multiple queries in a single transaction to ensure that they are either both successful or neither. The above question has an example of this.
Upvotes: 1
Reputation: 37233
It's not possible with one query as INSERT can only insert data to one table in mysql. You can either
You can wrap those inserts in transaction if you need to make sure that both queries will write the data
use those queries
$query1 ="INSERT INTO sales (user, date) values(.....)";
$query2 ="INSERT INTO settings (price) values(......)";
Upvotes: 0
Reputation: 1290
just do it with 2 queries
INSERT INTO sales (user, date) values('user', now());
INSERT INTO settings (price) values(100);
Upvotes: 1