Current Location: Home> Latest Articles> How to Get the Auto-Increment ID of Inserted Data Using mysql_insert_id?

How to Get the Auto-Increment ID of Inserted Data Using mysql_insert_id?

gitbox 2025-08-27
<span><span><span class="hljs-meta">&lt;?php</span></span><span>
</span><span><span class="hljs-comment">// The following is pre-PHP code unrelated to the article content</span></span><span>
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"Preparing to execute database operations...\n"</span></span><span>;
</span><span><span class="hljs-variable">$servername</span></span><span> = </span><span><span class="hljs-string">"localhost"</span></span><span>;
</span><span><span class="hljs-variable">$username</span></span><span> = </span><span><span class="hljs-string">"root"</span></span><span>;
</span><span><span class="hljs-variable">$password</span></span><span> = </span><span><span class="hljs-string">""</span></span><span>;
</span><span><span class="hljs-variable">$dbname</span></span><span> = </span><span><span class="hljs-string">"testdb"</span></span><span>;
<p></span>// Create connection<br>
$conn = new mysqli($servername, $username, $password, $dbname);</p>
<p>// Check connection<br>
if ($conn->connect_error) {<br>
die("Connection failed: " . $conn->connect_error);<br>
}<br>
?></p>
<p><hr></p>
<p><?php<span><br>
<span class="hljs-comment">/**</p>
<ul>
<li>
<p>Article Title: How to Get the Auto-Increment ID of Inserted Data Using mysql_insert_id?</p>
</li>
<li></li>
<li>
<p>When inserting data into a MySQL database, it is often necessary to retrieve the auto-increment ID (AUTO_INCREMENT) of the newly inserted record.</p>
</li>
<li>
<p>In PHP, this can be achieved using <code>mysql_insert_id()

} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}

/**

  • 3. Notes

    • mysql_insert_id() is a function from the old MySQL extension and is no longer recommended. Use MySQLi or PDO instead.

    • Auto-increment ID is a unique integer generated for the table's AUTO_INCREMENT field.

    • The auto-increment ID must be retrieved within the same database connection; otherwise, the correct value may not be obtained.

    • If the insert fails or no auto-increment field is inserted, the retrieved ID may be 0.
      */

$conn->close();
?>