search
HomeBackend DevelopmentPHP Tutorial【PHP】MySQL获取插入数据的主键(自增加ID),mysql主键_PHP教程

【PHP】MySQL获取插入数据的主键(自增加ID),mysql主键

 

为防止主键冲突,设计DB的时候常常使用自增加(auto_increment 型)字段。因此插入数据前往往不知道改记录的主键是什么,为了方便后续或级联查询,我们需要在插入一行记录后获得DB自动生成的主键。这里稍微整理了下几种方法:

 

  • DB中查询
<p><span><strong>通用:</strong></span></p>

<pre class="code"><span>SELECT</span> <span>max</span>(id) <span>FROM</span> <span>user</span>;

这个方法的缺点是不适合高并发。如果同时插入的时候返回的值可能不准确。

MySQL:

<span>SELECT</span> LAST_INSERT_ID();

重点: 假如你使用一条INSERT语句插入多个行, LAST_INSERT_ID() 只返回插入的第一行数据时产生的值。其原因是这使依靠其它服务器复制同样的 INSERT语句变得简单。

MS-SQL SERVER:

<span>select</span> <span>@@IDENTITY</span>;

@@identity是表示的是最近一次向具有identity属性(即自增列)的表插入数据时对应的自增列的值,是系统定义的全局变量。一般系统定义的全局变量都是以@@开头,用户自定义变量以@开头。比如有个表A,它的自增列是id,当向A表插入一行数据后,如果插入数据后自增列的值自动增加至101,则通过select @@identity得到的值就是101。使用@@identity的前提是在进行insert操作后,执行select @@identity的时候连接没有关闭,否则得到的将是NULL值。


补充:
SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTITY 在功能上相似,因为它们都返回插入到 IDENTITY 列中的值。 

IDENT_CURRENT 不受作用域和会话的限制,而受限于指定的表。IDENT_CURRENT 返回为任何会话和作用域中的特定表所生成的值。有关更多信息,请参见 IDENT_CURRENT。

SCOPE_IDENTITY 和 @@IDENTITY 返回在当前会话中的任何表内所生成的最后一个标识值。但是,SCOPE_IDENTITY 只返回插入到当前作用域中的值;@@IDENTITY 不受限于特定的作用域。

 

  • 服务器语言查询
<p><span><span><strong>PHP: mysql_insert_id(<em>connection</em>);</strong>    or    <strong>mysqli_insert_id(<em>connection</em>)<em>;</em></strong></span></span></p>
<p>参数   <em>connection</em>

    </p>
<p>描述   必需。规定要使用的 MySQL 连接。</p>

<pre class="code"><?<span>php
</span><span>$con</span> = <span>mysql_connect</span>("localhost", "hello", "321"<span>);
</span><span>if</span> (!<span>$con</span><span>)
  {
  </span><span>die</span>('Could not connect: ' . <span>mysql_error</span><span>());
  }

</span><span>$db_selected</span> = <span>mysql_select_db</span>("test_db",<span>$con</span><span>);

</span><span>$sql</span> = "INSERT INTO person VALUES ('Carter','Thomas','Beijing')"<span>;
</span><span>$result</span> = <span>mysql_query</span>(<span>$sql</span>,<span>$con</span><span>);
</span><span>echo</span> "ID of last inserted record is: " . <span>mysql_insert_id</span><span>();

</span><span>mysql_close</span>(<span>$con</span><span>);
</span>?>
<?<span>php
</span><span>$con</span>=<span>mysqli_connect</span>("localhost","my_user","my_password","my_db"<span>);
</span><span>//</span><span> Check connection</span>
<span>if</span> (<span>mysqli_connect_errno</span>(<span>$con</span><span>))
{
</span><span>echo</span> "Failed to connect to MySQL: " . <span>mysqli_connect_error</span><span>();
}

</span><span>mysqli_query</span>(<span>$con</span>,"<span>INSERT INTO Persons (FirstName,LastName,Age) 
VALUES ('Glenn','Quagmire',33)</span>"<span>);

</span><span>//</span><span> Print auto-generated id</span>
<span>echo</span> "New record has id: " . <span>mysqli_insert_id</span>(<span>$con</span><span>); 

</span><span>mysqli_close</span>(<span>$con</span><span>);
</span>?>

 

补充:

PHP-MySQL 是 PHP 操作 MySQL 资料库最原始的 Extension ,PHP-MySQLi 的 i 代表 Improvement ,提更了相对进阶的功能,就 Extension 而言,本身也增加了安全性。

a. mysql与mysqli的概念相关:

  • mysql与mysqli都是php方面的函数集,与mysql数据库关联不大。
  • 在php5版本之前,一般是用php的mysql函数去驱动mysql数据库的,比如mysql_query()的函数,属于面向过程3、在php5版本以后,增加了mysqli的函数功能,某种意义上讲,它是mysql系统函数的增强版,更稳定更高效更安全,与mysql_query()对应的有mysqli_query(),属于面向对象,用对象的方式操作驱动mysql数据库

b. mysql与mysqli的区别:

  • mysql是非持继连接函数,mysql每次链接都会打开一个连接的进程。
  • mysqli是永远连接函数,mysqli多次运行mysqli将使用同一连接进程,从而减少了服务器的开销。mysqli封装了诸如事务等一些高级操作,同时封装了DB操作过程中的很多可用的方法。

c. mysql与mysqli的用法:

  • mysql(过程方式):
<span>$conn</span> = <span>mysql_connect</span>('localhost', 'user', 'password'); <span>//</span><span>连接mysql数据库</span>
<span>mysql_select_db</span>('data_base');     <span>//</span><span>选择数据库</span>
<span>$result</span> = <span>mysql_query</span>('select * from data_base');<span>//</span><span>第二个可选参数,指定打开的连接</span>
<span>$row</span> = <span>mysql_fetch_row</span>( <span>$result</span> ) ) <span>//</span><span>只取一行数据</span>
<span>echo</span> <span>$row</span>[0]; <span>//</span><span>输出第一个字段的值</span>

PS:mysqli以过程式的方式操作,有些函数必须指定资源,比如mysqli_query(资源标识,SQL语句),并且资源标识的参数是放在前面的,而mysql_query(SQL语句,'资源标识')的资源标识是可选的,默认值是上一个打开的连接或资源。

  • mysqli(对象方式):
<span>$conn</span> = <span>new</span> mysqli('localhost', 'user', 'password','data_base');  <span>//</span><span>要使用new操作符,最后一个参数是直接指定数据库
//假如构造时候不指定,那下一句需要$conn -> select_db('data_base')实现</span>

<span>$result</span> = <span>$conn</span> -> query( 'select * from data_base'<span> );
</span><span>$row</span> = <span>$result</span> -> fetch_row(); <span>//</span><span>取一行数据</span>
<span>echo</span> row[0]; <span>//</span><span>输出第一个字段的值</span>

使用new mysqli('localhost', usenamer', 'password', 'databasename');会报错,提示如下:

Fatal error: Class 'mysqli' not found in ...

一般是mysqli是没有开启的,因为mysqli类不是默认开启的,win下要改php.ini,去掉php_mysqli.dll前的;,linux下要把mysqli编译进去。

d. mysql_connect()与mysqli_connect()

  • 使用mysqli,可以把数据库名称当作参数传给mysqli_connect()函数,也可以传递给mysqli的构造函数;
  • 如果调用mysqli_query()或mysqli的对象查询query()方法,则连接标识是必需的。

JDBC 2.0:insertRow()

Statement stmt = <span>null</span><span>;
ResultSet rs </span>= <span>null</span><span>;
</span><span>try</span><span> {
    stmt </span>= conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,  <span>//</span><span> 创建Statement</span>
<span>                                java.sql.ResultSet.CONCUR_UPDATABLE);
    stmt.executeUpdate(</span>"DROP TABLE IF EXISTS autoIncTutorial"<span>);
    stmt.executeUpdate(                                                </span><span>//</span><span> 创建demo表</span>
            "CREATE TABLE autoIncTutorial ("
            + "priKey INT NOT NULL AUTO_INCREMENT, "
            + "dataField VARCHAR(64), PRIMARY KEY (priKey))"<span>);
    rs </span>= stmt.executeQuery("SELECT priKey, dataField "                 <span>//</span><span> 检索数据</span>
       + "FROM autoIncTutorial"<span>);
    rs.moveToInsertRow();                                              </span><span>//</span><span> 移动游标到待插入行(未创建的伪记录)</span>
    rs.updateString("dataField", "AUTO INCREMENT here?");              <span>//</span><span> 修改内容</span>
    rs.insertRow();                                                    <span>//</span><span> 插入记录</span>
    rs.last();                                                         <span>//</span><span> 移动游标到最后一行</span>
    <span>int</span> autoIncKeyFromRS = rs.getInt("priKey");                        <span>//</span><span> 获取刚插入记录的主键preKey</span>
<span>    rs.close();
    rs </span>= <span>null</span><span>;
    System.out.println(</span>"Key returned for inserted row: "
        +<span> autoIncKeyFromRS);
}  </span><span>finally</span><span> {
    </span><span>//</span><span> rs,stmt的close()清理</span>
}

JDBC 3.0:getGeneratedKeys()

Statement stmt = <span>null</span><span>;
ResultSet rs </span>= <span>null</span><span>;
</span><span>try</span><span> {
    stmt </span>=<span> conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
                                java.sql.ResultSet.CONCUR_UPDATABLE);  
    </span><span>//</span><span> ...
    </span><span>//</span><span> 省略若干行(如上例般创建demo表)
    </span><span>//</span><span> ...</span>
<span>    stmt.executeUpdate(
            </span>"INSERT INTO autoIncTutorial (dataField) "
            + "values ('Can I Get the Auto Increment Field?')"<span>,
            Statement.RETURN_GENERATED_KEYS);                      </span><span>//</span><span> 向驱动指明需要自动获取generatedKeys!</span>
    <span>int</span> autoIncKeyFromApi = -1<span>;
    rs </span>= stmt.getGeneratedKeys();                                  <span>//</span><span> 获取自增主键!</span>
    <span>if</span><span> (rs.next()) {
        autoIncKeyFromApi </span>= rs.getInt(1<span>);
    }  </span><span>else</span><span> {
        </span><span>//</span><span> throw an exception from here</span>
<span>    } 
    rs.close();
    rs </span>= <span>null</span><span>;
    System.out.println(</span>"Key returned from getGeneratedKeys():"
        +<span> autoIncKeyFromApi);
}  </span><span>finally</span> { ... }

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/971765.htmlTechArticle【PHP】MySQL获取插入数据的主键(自增加ID),mysql主键 为防止主键冲突,设计DB的时候常常使用自增加(auto_increment 型)字段。因此插入数据...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)