title: Mysql_error() Not Catching INSERT Error in PHP
body: <p>new here and really green to programming, so go easy..</p>
  
  <p>I discovered I have an <code>INSERT</code> that is failing because of a duplicate record error. I figured it out by running the query in a MySQL console with literals, where err#1062 popped up.</p>
  
  <p>What I want to understand is why <code>mysql_error()</code> or <code>mysql_errno()</code> didn't catch this error in my PHP script. </p>
  
  <p>Below is a generic setup of what I've done. I have a form that submits to a php file that calls <code>data_insert()</code></p>
  
  <pre><code>function data_insert($var1, $var2, $var3, $var4){
  
      $db = db_connect();
      $query = "INSERT INTO exampletable (id, id_2, id_3, id_4) 
              VALUES ('$var1', '$var2', '$var3', '$var4')";
  
      $result = $db-&gt;query($query);
          if (!$result) 
              { 
              echo ('Database Error:' . mysql_error());
              } 
          else 
              {
              echo "Data added to db";
              }
  }
  </code></pre>
  
  <p>The DB connection:</p>
  
  <pre><code>function db_connect()
  {
      $result = new MySQLi('localhost', 'root', 'root', 'dbname');
      if (!$result)
          throw new Exception('Could not connect to database server');
      else
          return $result;
  }
  </code></pre>
  
  <p>Result I'm getting is:</p>
  
  <pre><code>Database Error:
  </code></pre>
  
  <p>PHP echos "Database Error:" because the <code>INSERT</code> fails, but no subsequent MySQL error info is echoed. Honestly, I'm not exactly sure what I'm supposed to see, but through reading some other SO questions, I've double-checked my php.ini file for error handling and E_ALL and display_errors is set appropriately (although not sure if it matters in this case).</p>
  
  <p>Is there something in my logic that I'm not understanding, like the scope of the link resource mysql_error() takes? </p>
  
  <p>Thanks for your help, I'm hoping this is something embarrassingly obvious. </p>
  
  <p><em>I know the above is missing XSS and security precautions and uniform exception handling. Baby steps though. It's simplified here for discussion's sake.</em>  </p>