如何获得插入的结果 [英] How to get result of Insert

查看:31
本文介绍了如何获得插入的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当基本的问题,我目前有两个表,在第二个表中有一个表 A 的外键列.

This is a fairly basic question, I currently have two tables and in the second table there is a foreign key column for table A.

id       Name
----------------
1        Name1
2        Name2

表 B:

id       Name      Parent
-------------------------
1        John      1

发生了什么:

  • 我的 PHP 脚本将 Name1 插入到表 A 中,然后 mysql 插入 id.
  • 我的 PHP 脚本需要将 John 插入表 B 并将 Parent 设置为表的 id刚刚插入的查询.
  • My PHP script inserts Name1 into Table A and mysql inserts the id.
  • My PHP script needs to insert John into Table B AND set Parent to be the id of the query that was just inserted.

推荐答案

第一次插入后,您可以:

After the first insert, you can do:

$res = mysql_query('SELECT LAST_INSERT_ID()');
$row = mysql_fetch_array($res);
$lastInsertId = $row[0];

或者,您可以使用 mysql_insert_id.但是,从手册中:

Alternatively, you can use mysql_insert_id. However, from the manual:

mysql_insert_id() 将转换原生 MySQL C API 的返回类型函数 mysql_insert_id() 到一个类型long(在 PHP 中命名为 int).如果你的AUTO_INCREMENT 列有一个列BIGINT 类型(64 位)转换可能会导致错误 而是使用内部 MySQLSQL 函数 LAST_INSERT_ID()SQL 查询.

mysql_insert_id() will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query.

因此,如果您的专栏使用 - 或将来可能使用 - BIGINT,则首选我列出的第一种方法.

Because of this, the first method I listed is preferred if your column uses -- or may use in the future -- BIGINT.

这篇关于如何获得插入的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆