title: PHP mysqli random error during insert
body: <p>I migrate data from a mysql database to another mysql database with different schema using a PHP script. The entity currently I am working on is very simple. It is users data. All of my database tables have <code>utf8_general_ci</code> collation to support Arabic text.</p>
  
  <p>I may receive the following error:</p>
  
  <blockquote>
    <p>Failed to run query #14: (1064) You have an error in your SQL syntax;
    check the manual that corresponds to your MySQL server version for the
    right syntax to use near 'ايمان مصطفى', '1425827057', 0, 0, 1,
    'Africa/Cairo', '', 0)' at line 1</p>
  </blockquote>
  
  <p>The unexpected thing here: When I delete the newly added records to the destination database before the stop due to the error and running my script again, I got the same error but for another record!</p>
  
  <p>In the error regarded above you may notice that the Arabic name <code>ايمان مصطفى</code> in the query is missing one of the two single quote <code>'</code>. However, I'm sure that my script enclose the values with single quotes as the following:</p>
  
  <pre><code>$sqlFormat = "INSERT INTO users (uid, name, pass, theme, signature, created, access, login, status, timezone, language, picture) VALUES ('%s', '%s', '%s', '', '%s', '%s', 0, 0, 1, '%s', '', 0)";
      $sql = sprintf($sqlFormat, $user['uid'], $user['name'], $user['pass'], $user['signature'], $user['created'], $user['timezone']);
      $res2 = mysqli_query($db2, $sql);
      if (!$res2) {
          echo "Failed to run query #$i: (" . $db2-&gt;errno . ") " . $db2-&gt;error;
          echo "\n";
          echo $sqlInsert;
          if ($db2-&gt;errno != 1062) {
              exit();
          }
  </code></pre>
  
  <h3>Edit</h3>
  
  <p>This is an example for the random error generated with a printout for the <code>INSERT</code> sql statement delivered to the query:</p>
  
  <pre><code>Failed to run query #4: (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'عبد العزيز كحيل', '1425828804', 0, 0, 1, 'Africa/Cairo', '', 0)' at line 1
  
  INSERT INTO users (uid, name, pass, theme, signature, created, access, login, status, timezone, language, picture) VALUES ('149', 'عبد العزيز كحيل', 'U.GCK9X7@$7-w$1@lZQ5HZ=x}M(@a5D}&lt;`Cdod13aJ8O/&amp;&amp;&gt;0%w7jUrKm[bX\', '', 'عبد العزيز كحيل', '1425828804', 0, 0, 1, 'Africa/Cairo', '', 0)
  </code></pre>
  
  <p>You may notice that the Arabic name <code>عبد العزيز كحيل</code> is surrounded correctly with two single quotes for the value for <code>name</code> field, but it is missing a trailing single quote for the <code>signature</code> field.</p>
  
  <p>My problems are:</p>
  
  <ul>
  <li>I need to know why this error is generated randomly?</li>
  <li>How to avoid this error?</li>
  </ul>