title: Mysql insert if not exists without unique constraint (don't want to rely on rolling back errors) (PHP + PDO)
body: <p>I am making a registration page. I'm worrying about concurrency issues where two users register with the same username at the same time (know it's real rare, but hate having small flaws in code).</p>
  
  <p>So my approach is, check if the username exists, and if not, insert a new row. I'm using PDO</p>
  
  <p><strong>What I've tried</strong></p>
  
  <p>I'm using transactions, but from my question here <a href="https://stackoverflow.com/questions/11132696/how-exactly-do-transactions-with-php-pdo-work-with-concurrency">How exactly do transactions with PHP PDO work with concurrency?</a> it appears that two transactions can read at the same time</p>
  
  <ul>
  <li>I don't think I can use <code>select...for update</code> because I am not updating; in fact, I need to lock an "imaginary" row where a new entry will be added, if it does not exist already</li>
  <li>I've tried googling some examples, but they don't seem to handle the concurrency issue mentioned above <a href="http://php.about.com/od/finishedphp1/ss/php_login_code_2.htm" rel="nofollow noreferrer">http://php.about.com/od/finishedphp1/ss/php_login_code_2.htm</a></li>
  </ul>
  
  <p><strong>Solution?</strong></p>
  
  <p>I've googled and added a <code>UNIQUE</code> constraint on the username field, but do not want to rely on a MySQL error to rollback the transaction. I'm no expert, but it just doesn't feel elegant to me. <strong>So is there a way to <code>insert if not exists</code> with pure MySQL?</strong></p>
  
  <p>Now, if this really is the way to go, I've got a couple questions. <strong>If a warning is thrown, does that stop the queries?</strong> Like will it throw the exception shown in the example here <a href="https://stackoverflow.com/questions/2708237/php-mysql-transactions-examples">PHP + MySQL transactions examples</a> ? Or will only a downright-error throw the exception?</p>
  
  <p>Also, it seems to imply here <a href="https://stackoverflow.com/questions/47589/can-i-detect-and-handle-mysql-warnings-with-php">Can I detect and handle MySQL Warnings with PHP?</a> that warnings will show up somehow in the PHP output, but I've never had "visible MySQL errors." The question was not using PDO like in my code, but I was just wondering. <strong>Do MySQL errors and warnings make html output? Or does it only say something if I call<code>errorInfo()</code>?</strong></p>
  
  <p>Thanks</p>