【问题标题】:How to know the ID of an auto incremented column in a "one to many" database? [duplicate]如何知道“一对多”数据库中自动递增列的 ID? [复制]
【发布时间】:2017-09-28 04:42:07
【问题描述】:

我的数据库由 2 个具有“一对多”关系的表组成

the first table:

CREATE TABLE data (
  personid int not null auto_increment,
  name varchar(255),
  phone int ,
  primary key (personid)
)

第二张桌子:

CREATE TABLE links (
  linkid int not null auto_increment,
  link varchar(255),
  personid int,
  primary key (linkid),
  foreign key (personid)
    references data(personid)

)

我在第一个表中插入记录,每条新记录都有一个新ID,然后输入这个ID的链接,我想知道如何知道这个人的ID通过php/sql插入链接给他

【问题讨论】:

  • 在第一个表中插入后获取最后插入的 id,然后将该 id 用于第二个表

标签: php mysql sql mysqli pdo


【解决方案1】:

使用MysqliPDO -

使用 PDO:

$personid = $pdo->lastInsertId();

使用 Mysqli:

$personid = $mysqli->insert_id;

然后使用上面的$personid再次插入数据links表数据。

您必须开始使用MysqliPDOPHP 中编写代码。

保持标准:)

【讨论】:

  • 如果 id 已经存在并且我想知道这个 id 以添加更多指向这个 id 的链接怎么办?
  • Danny - 如果之前插入的 ID 已经存在,则需要运行单独的 SELECT 查询才能找到它。如果您只想知道最近插入的 ID 以插入到第二个表中,那么此方法将起作用。
猜你喜欢
  • 1970-01-01
  • 2016-03-31
  • 2013-04-10
  • 2011-09-16
  • 2018-01-22
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 2016-04-11
相关资源
最近更新 更多