title: MySQL - How to insert into table that has many-to-many relationship
body: <p>I have a table of persons. Each person has a property and many persons may have a certain property. So this is a many-to-many relationship. This is the schema:</p>
  
  <pre><code>CREATE TABLE persons (
    person_id int(11) NOT NULL AUTO_INCREMENT,
    firstname varchar(30) NOT NULL,
    lastname varchar(30) NOT NULL,
    PRIMARY KEY (person_id)
  );
  
  CREATE TABLE properties (
    property_id int(11) NOT NULL AUTO_INCREMENT,
    property varchar(254) NOT NULL UNIQUE,
    PRIMARY KEY (property_id)
  );
  
  CREATE TABLE has_property (
    person_id int(11) NOT NULL,
    property_id int(11) NOT NULL,
    PRIMARY KEY (person_id,property_id),
    FOREIGN KEY (person_id) REFERENCES persons (person_id),
    FOREIGN KEY (property_id) REFERENCES properties (property_id)
  );
  </code></pre>
  
  <p>Now lets say i want to insert to the database this person:</p>
  
  <ul>
  <li>firstname:'John'</li>
  <li>lastname:'Doe'</li>
  <li>properties:'property_A','property_B','property_C'</li>
  </ul>
  
  <p>persons</p>
  
  <pre><code>+-----------+-----------+----------+
  | person_id | firstname | lastname |
  +-----------+-----------+----------+
  |         1 | John      | Doe      |
  +-----------+-----------+----------+
  </code></pre>
  
  <p>properties</p>
  
  <pre><code>+-------------+------------+
  | property_id |  property  |
  +-------------+------------+
  |           1 | property_A |
  |           2 | property_B |
  |           3 | property_C |
  +-------------+------------+
  </code></pre>
  
  <p>has_property</p>
  
  <pre><code>+-----------+-------------+
  | person_id | property_id |
  +-----------+-------------+
  |         1 |           1 |
  |         1 |           2 |
  |         1 |           3 |
  +-----------+-------------+
  </code></pre>
  
  <p>So far the best thing i have thought is to do a regular insert in the persons table:</p>
  
  <pre><code>INSERT INTO persons (firstname,lastname) VALUES ('John','Doe');
  </code></pre>
  
  <p>and then do a select to find the id of the person i just inserted</p>
  
  <pre><code>SELECT person_id FROM persons WHERE firstname='John' AND lastname='Doe';
  </code></pre>
  
  <p>in order to insert into the other two tables (because i need to know the person_id). 
  But i think there must be a better way, isn't it?</p>