title: How does PDO know last inserted id in MySQL?
body: <p><strong>EDIT:</strong> This question title originally was: <em>How does Doctrine know last inserted id in MySQL?</em> and was related to <em>Doctrine</em> ORM mapper. After some digging I found out that this question is not related to <em>Doctrine</em> but to <em>PDO_MySQL</em>, <em>MySQL C API</em> and finally - to MySQL client-server communication. I have decided to change the title, so maybe someone will find answer to his/hers question.</p>
  
  <p>For those who are not using Doctrine: I was curious, why bellow:</p>
  
  <pre><code>mysql_query("INSERT INTO category (name) VALUES('cat')");
  echo mysql_insert_id();
  </code></pre>
  
  <p>or similar:</p>
  
  <pre><code>$pdo-&gt;exec("INSERT INTO category (name) VALUES('cat')");
  echo $pdo-&gt;lastInsertId();
  </code></pre>
  
  <p>will lead to only one position (without separate <code>SELECT LAST_INSERT_ID()</code>) in log:</p>
  
  <pre><code>1701 Query    INSERT INTO category (name) VALUES ('cat')
  </code></pre>
  
  <p><strong>Original question:</strong></p>
  
  <p>I have 2 tables:</p>
  
  <pre><code>category(id,name)
  product(id, name, categoryId)
  </code></pre>
  
  <p>I created new category object and product object. I assigned category object to product object. I didn't set any ids:</p>
  
  <pre><code>$product = new Product();
  $product-&gt;name = 'asdf';
  
  $category = new Category();
  $category-&gt;name = 'cat';
  
  $product-&gt;Category = $category;
  </code></pre>
  
  <p>After that I flushed the connection and check MySQL logs:</p>
  
  <pre><code>1684 Query  START TRANSACTION
  1684 Query  INSERT INTO category (name) VALUES ('cat')
  1684 Query  INSERT INTO product (name, categoryid) VALUES ('asdf', '312')
  1684 Query  COMMIT
  </code></pre>
  
  <p>How did Doctrine know, that the newly created category id is 312? There is nothing else in logs.</p>