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

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

WBOY
Release: 2016-07-13 10:01:55
Original
1128 people have browsed it

【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 型)字段。因此插入数据...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template