PHP中mysql_insert_id()函數擷取最後插入記錄ID編號

來源:互聯網
上載者:User

這個問題以前絕壁遇到過,太久沒寫不記得(貌似當時是CI架構直接有相關函數的),然後這次又遇到了,再次滾去查了一下,這裡說的並非是PDO之類的情況,而是用過時的串連和執行方式之後怎麼進行操作。

有什麼SQL語句實現的,但明顯不合適,當收到多人操作時,頓時就混亂不堪。

所以在此,用mysql_insert_id()函數搞定,他會返回AUTO_INCRESEMENT的值。

 代碼如下 複製代碼

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d ", mysql_insert_id());
?>

剛開始我還在想這個函數不會遇到相同的問題麼,然後小新告訴我是基於當前資料庫連接的,頓時不怕不怕啦。

當然還有

 代碼如下 複製代碼

mysql_query("select max(id) from t1",$link);

當然,現在這種串連方式已經out的可以了,


這裡也有說明:

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

mysqli_insert_id()
PDO::lastInsertId()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.