php - In transaction insert same key for two tables (1. primary 2. foreign) -


i have in code 2 queries. (in real code have 6 queries , need transaction).

i don't know how variable $category_id cause category isn't putted yet in database (it should inserted in same time - or nothing)

code:

try {     $this->mysqli->begin_transaction();      $this->mysqli->query("insert `category` (`name`) values ('$category')");     $this->mysqli->query("insert `subcategory` (`name`,`category_id` ) values ('$subcategory','$category_id')");      $this->mysqli->commit();  } catch (exception $e) {     echo $e;     $this->mysqli->rollback(); } 

mysql tables:

    category:     ---------     |id|name|      subcategory:     |id|name|category_id| 

so need solution how know before query value of $category_id, or how modify query category_id in database filed.

last_insert_id() want here.

try {     $this->mysqli->begin_transaction();      $this->mysqli->query("insert `category` (`name`) values ('$category')");     $this->mysqli->query("insert `subcategory` (`name`,`category_id` ) values ('$subcategory', last_insert_id())");      $this->mysqli->commit();  } catch (exception $e) {     echo $e;     $this->mysqli->rollback(); } 

p.s. prepared statements, instead of concatenating variables query.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

visual studio 2010 - Connect to informix database windows form application -

android - Associate same looper with different threads -