Table of Contents
【PHP】MySQL获取插入数据的主键(自增加ID),mysql主键
Home Backend Development PHP Tutorial 【PHP】MySQL获取插入数据的主键(自增加ID),mysql主键_PHP教程

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

Jul 13, 2016 am 10:01 AM
mysql

【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>;
Copy after login

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

MySQL:

<span>SELECT</span> LAST_INSERT_ID();
Copy after login

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

MS-SQL SERVER:

<span>select</span> <span>@@IDENTITY</span>;
Copy after login

@@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>?>
Copy after login
<?<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>?>
Copy after login

补充:

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>
Copy after login

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>
Copy after login

使用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>
}
Copy after login

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> { ... }
Copy after login

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/971765.htmlTechArticle【PHP】MySQL获取插入数据的主键(自增加ID),mysql主键 为防止主键冲突,设计DB的时候常常使用自增加(auto_increment 型)字段。因此插入数据...
Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

See all articles