php - Last insert id issue--How to fetch it -



php - Last insert id issue--How to fetch it -

i'm using $id = mysqli_insert_id($connection); lastly inserted id, in case if updates record in table, returns 0 lastly inserted id.

is there way handle this?

i want id each time weather it's inserting or updating.

thanks

edit

i need id used inserting info table2

id tab1 set info tab2 id tab1 fk

and important, i'm not using update where clause

here code i'm using

$val = utf8_encode($val); mysqli_set_charset($connection, 'utf8'); mysqli_query($connection, "set names 'utf8'"); mysqli_query($connection, "set foreign_key_checks = 0;"); $sql = "insert leaks($insert) values($val)"; $sql .= " on duplicate key update `url` = '".mysqli_real_escape_string($connection,$data['url'])."';"; mysqli_query($connection, ($sql))or die(mysqli_error($connection)."<br />".print($sql)); $id = mysqli_insert_id($connection); $proofs['leaks_id'] = $id; mysqli_query($connection, "set foreign_key_checks = 0;"); print_r($id); $this->insertproofs($connection, $proofs); connection::close_connection($connection);

please note downwards $this->insertproofs($connection, $proofs); inserts info table2 on base of operations of key passed it

on insert

after executing insert query, using mysqli_insert_id() absolutely fine.

on update

depending on update, you;

would know id's you're updating know criteria search id's update.

for example, if update like;

update `foo` set `x`='y' `a`='b'

you can run

select `id` `foo` `a`='b'

to fetch updated id's.

edit

i see you're using on duplicate key update.

you can modify query become (assuming id primary auto_increment key)

on duplicate key update `url` = '".mysqli_real_escape_string($connection,$data['url'])."', id = last_insert_id(id)

then can utilize mysqli_insert_id() regardless of if update or insert

for example, if run (with record of id=2 exists; we'll update);

insert foobar (id, foo) values (2, 'bar') on duplicate key update foo = 'baz', id = last_insert_id(id); select last_insert_id();

the output 2, lastly insert id.

php mysqli

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -