开发者

How to insert a row's primary key in to another one of its columns?

I find myself doing this a lot:

mysql_query("INSERT INTO employees (name, age) VA开发者_如何学JAVALUES ('$name', '$age')");
$id = mysql_insert_id();
mysql_query("UPDATE employees SET pID = $id WHERE id = '$id'");

This is just an example but I often need to include the newly inserted row's ID in to another one of its columns and I am forced to use this cumbersome solution. Is there any other way?


Since you don't know what the insert id is beforehand, there is no other way to do this (short of getting the max ID and using it in the insert query, but that's still another query). Why do you need to do it "a lot," though? Create a function that will do just that for you.

The better question is: why do you need the ID to be in two columns in the same table?


You can do it in a single call from php to mysql if you use a stored procedure:

Example calls

call insert_employee('f00',32);
call insert_employee('bar',64);

$sql = sprintf("call insert_employee('%s',%d)", $name, $age);

Script

drop table if exists employees;
create table employees
(
id int unsigned not null auto_increment primary key,
name varchar(32) not null,
age tinyint unsigned not null default 0,
pid int unsigned not null default 0
)
engine=innodb;

drop procedure if exists insert_employee;

delimiter #

create procedure insert_employee
(
in p_name varchar(32),
in p_age tinyint unsigned
)
begin

declare v_id int unsigned default 0;

  insert into employees(name, age) values (p_name, p_age);
  set v_id = last_insert_id();
  update employees set pid = v_id where id = v_id;
end#

delimiter ;


Check MySQL's LAST_INSERT_ID() function here. May or may not be what you need depending on your situation.


@John Smith - there are differing models of heirarchial data - yourchosen one can be difficult to work with...

have a look at some other methods


http://php.net/manual/en/function.mysql-insert-id.php

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜