2011-03-21 85 views
0

我有以下表格:将数据插入到两个或多个表:

thread: id, title, content, created 
thread_tags: tag_id, thread_id 
tag: id, name 
author_threads: thread_id, author_id 

为了创建一个线程所有这些领域必须填写(ID被明显自动递增)。我知道我可以使用SQL TRANSACTIONS来确保它们都被填充或不填充,但是我怎样才能从最后的sql语句中填充tag_id,thread_id,author_id和thread_id(在author_threads中)呢?没有交易,我会使用mysqli_last_insert_id。

我也应该使用mysqli::multi_query?基本上我怎么去确保所有这些字段都被填入?

哦,我正在使用PHP和MYSQL。

编辑:

将这项工作?

$sql_thread = "START TRANSACTION; 
        INSERT INTO thread (title, content) 
        VALUES ('some title', 'some content')"; 

    # this is normally a loop, as there are more than one tags: 
    $sql_tags = "INSERT INTO tag (name) 
       VALUES ('onetag')"; 


    # normally I would check the return value 
    mysqli_query($link, $sql_thread); 

    # get the thread id: 
    $thread_id = mysqli_insert_id($link); 

    mysqli_query($link, $sql_tags); 

    # get the tag id: 
    $tag_id = mysqli_insert_id($link); 

    # insert into thread_tags: 
    mysqli_query($link, "INSERT INTO thread_tags (thread_id, tag_id) VALUES ($thread_id, $tag_id)"); 

    # insert into author_threads, I already know author_id: 
    mysqli_query($link, "INSERT INTO author_threads (author_id, thread_id) VALUES ($author_id, $thread_id) 
         COMMIT;"); 
+0

为什么你不能通过mysqli_insert_id()以同样的方式来做到这一点? – Matthew 2011-03-21 23:37:52

+0

我想你正在寻找'LAST_INSERT_ID()'函数。 – 2011-03-21 23:40:17

+0

我希望他们都被填写,或者不填写。因此交易? – 2011-03-21 23:41:07

回答

1

对我来说,它看起来像你已经知道答案:使用mysqli_insert_id()SELECT LAST_INSERT_ID()。您应该使用他们的交易没有任何问题:

  • 开始交易
  • 插入行
  • 得到最后插入的id
  • 插入行,使用ID为外地链路
  • ...
  • 提交事务

如果失败,回滚事务,并且哟你什么也没有。

+0

你将如何使用mysqli_insert_id()的交易?另外我需要获得两次thread_id,那里的逻辑是什么? – 2011-03-21 23:54:58

+0

最后一个插入ID仍然适用于事务。即使数据尚未提交,当前事务仍然可以访问它。要多次使用线程ID,只需在创建线程记录后将其设置为某个变量(例如'$ thread_id = mysqli_insert_id($ db);')即可。 – Matthew 2011-03-22 00:03:46

+0

我已经更新了我的答案,这是否有效? – 2011-03-22 00:39:06