在相同页面上设置后立即获取ID

时间:2013-05-03 01:29:58

标签: php mysql last-insert-id

Thread_Body中的ThreadID需要是Thread_Titles id的id。 我该怎么做呢?

if (isset($_POST['Post_Thread'])) {
    if (empty($_POST['Post_Title'])) {
        echo "No Title No Thread.";
    } else {
        $Sec = mysql_real_escape_string($_GET['sec']);
        mysql_query("INSERT INTO Thread_Titles (Name, Section, Posted, Poster, Updated) VALUES('".cleanPost($_POST['Post_Title'])."', '".$Sec."', '".time()."', '".$ULN->Username."', '".time()."') ") or die(mysql_error()); 
    }
    if (empty($_POST['Post_Body'])) {
        echo "No Body No Thread.";
    } else {
        mysql_query("INSERT INTO Thread_Replies (Body, Posted, Poster, ThreadID) VALUES('".cleanPost($_POST['Post_Body'])."', '".time()."', '".$ULN->Username."', '".$ThreadID."') ") or die(mysql_error()); 
    }
}

这是所有期望表格的代码。

1 个答案:

答案 0 :(得分:1)

使用mysql_insert_id()

mysql_query("INSERT INTO Thread_Titles (Name, Section, Posted, Poster, Updated) VALUES('".cleanPost($_POST['Post_Title'])."', '".$Sec."', '".time()."', '".$ULN->Username."', '".time()."') ") or die(mysql_error());  
$ThreadID = mysql_insert_id();

仅供参考,you shouldn't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial