title: How exactly do transactions with PHP PDO work with concurrency?
body: <p>I'm making a webapp where they'll be multiple users interacting with each other and reading/making decisions on/modifying shared data.</p>
  
  <p>I've read that transactions are atomic, which is what I need. However, I'm not sure how it works with the PHP <code>PDO::beginTransaction()</code></p>
  
  <p>I mean atomic as in if one transaction is editing some data, all other transactions also modifying/reading that data will need to wait until the first transaction finishes. Like I don't want two scripts reading a value, incrementing the old one, and effectively storing only one increment. The second script should have to wait for the first one to finish.</p>
  
  <p>In almost all the examples I've seen the queries are used consecutively (example <a href="https://stackoverflow.com/questions/2708237/php-mysql-transactions-examples">PHP + MySQL transactions examples</a>). A lot of what I'm doing requires</p>
  
  <ul>
  <li>querying and fetching</li>
  <li>checking that data, and acting on it, as part of the same transaction</li>
  </ul>
  
  <hr>
  
  <ol>
  <li><strong>Will the transaction still work atomically if there is PHP code between queries?</strong></li>
  <li><strong>I know you should prepare your statements outside the transaction, but is it okay to prepare it inside? Basically, I'm worried about PHP activity ruining the atomicity of a transaction.</strong></li>
  </ol>
  
  <p>Here's an example (this one doesn't require checking a previous value). I have a very basic inbox system which stores mail as a serialized array (if someone has a better recommendation please let me know). So I query for it, append the new message, and store it. Will it work as expected?</p>
  
  <pre><code>$getMail = $con-&gt;prepare('SELECT messages FROM inboxes WHERE id=?');
  $storeMail = $con-&gt;prepare('UPDATE inboxes SET messages=? WHERE id=?');
  $con-&gt;beginTransaction();
  $getMail-&gt;execute(array($recipientID));
  $result = $getMail-&gt;fetch();
  $result = unserialize($result[0]);
  $result[] = $msg;
  $storeMail-&gt;execute(array(serialize($result), $recipientID));
  $con-&gt;commit();
  </code></pre>