0

I have 2 tables:

Table1

u_id    email
1       user1@y.com
2       user2@h.com

and Table2

id u_id values

had to insert values to table2 with u_id when user enters from form Example:I need to add the value table1 u_id while that user is logged in into table2 that is id increments in table and u_id from table1 and values as user enters from table2

i tried something this query however not successful

insert into table2 (u_id,values)
            values ((select u_id from table1), 'values')
GMB
  • 216,147
  • 25
  • 84
  • 135
rsethi
  • 35
  • 8

1 Answers1

1

The problem with your query is that the subquery returns multiple rows (one value per row in table1), while the database expects a scalar value.

I would expect that you know the email of the current user, and want to recover the corresponding u_id to insert a new row in table2, along with a literal value. If so, I would recommend the insert ... select syntax:

insert into table2 (u_id, val)
select u_id, 'foo' from table1 where email = 'user1@y.com'

Side note: values is a SQL keyword, hence not a good choice for a column name (you would need to quote this identifier every time you use it). I renamed this column to val in the query.

GMB
  • 216,147
  • 25
  • 84
  • 135
  • where is foo from . i mean what is that @GMB , Also im using session in php so i can write $email where email ='$email'; – rsethi May 16 '20 at 23:45
  • 1
    @rsethi: (1) `'foo'` is whatever fixed value you want to insert in column `val` (you can change it as per your requirement). (2) Yes, you should pass the user email as a parameter to the query (note that you you would better use a parameterized query rather than concatenating the parameter in the query string) . – GMB May 16 '20 at 23:48
  • how would you do parameterized query can you provide some example keeping in mind the same. I am newbie here – rsethi May 16 '20 at 23:50
  • @rsethi: there are lot of resources that you can find on the web, by searching for something like *php parameterized query*. You could start with [this famous SO post)[https://stackoverflow.com/q/60174/10676716]. – GMB May 17 '20 at 00:50