The task is as follows: there is a user table ( members ) and a unit table ( unit ), there is a unit column in the user table, how to add a unit to this column, for example, with id 1?

    3 answers 3

    Structure:

    • members - id,(some fields),unit_id
    • unit - id,(some fields).

    It is possible and necessary to associate unit_id and id from members . When inserting, first insert into unit , then substitute id unit into members. You can get the id Unit cl. way: through php + mysql, pull it out through the f-y mysql_insert_id , or already when pasting to members use the function mysql

     LAST_INSERT_ID(): INSERT into `members` VALUES (some fields, LAST_INSERT_ID()) 

    This is a general idea, once did, read how to use these functions and understand everything, if not - write, we will pedal the code. :)

      Based on the principle of working with databases, the unit field in the members table should store only the unit id. By this id in the units table you choose the unit you need from the base.

        If you correctly understood something like this:

         INSERT INTO table (SELECT * FROM another_table WHERE id="your_id"); 
        • one
          Why make an additional request to find out your_id. As I understand it, he has 2 requests for insertion into the database right away. First in the unit, then in the members. Here we insert - INSERT INTO unit VALUES (val1, val2, ..). The second query goes right after the first - INSERT into members VALUES (val1, val2, LAST_INSERT_ID (), ...); And that's all. Mysql already has many of its functions that allow you to get data without php) - Barton