2012-08-14 81 views
1

可能重複:
Select last insert id
Retrieving the last insert id from MySql using PHP如何從我剛執行的MYSQL插入中獲取主ID?

我想從一個插入我執行UNIQUE_ID。在我的MySQL數據庫中,column_1是一個唯一的ID,每次插入時都會自動遞增。

我認爲答案與$ mysqli-> insert_id有關,但我不確定它應該放在哪裏。下面是我使用,使插入代碼:

// Add the user to the database: 
$q = "INSERT INTO database_name (column_2, column_3, column_4) VALUES ('$val1', '$val2', '$val3')"; 
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); 

if (mysqli_affected_rows($dbc) == 1) { // If it ran OK. 

    $_SESSION['column_2'] = $val1; 
    $_SESSION['column_3'] = $val2; 
    $_SESSION['column_4'] = $val3; 

    //Do whatever 

    //Go-to page 

    $url = BASE_URL . 'url-address-of-thank-you-page'; . 
    ob_end_clean(); // Delete the buffer. 
    header("Location: $url"); 

    exit(); // Stop the page. 

} else { // If it did not run OK. 
    echo '<div class="error"><p>You could not be registered due to a system error. We apologize for any inconvenience.</p></div>'; 
} 

這裏是工作代碼:

... 
    $_SESSION['column_1'] = $dbc->insert_id; 
    $_SESSION['column_2'] = $val1; 
    $_SESSION['column_3'] = $val2; 
    $_SESSION['column_4'] = $val3; 

... 
+0

難道你已經嘗試把它只是你的查詢之後? http://php.net/manual/en/mysqli.insert-id.php應該這樣做。 – Sgarz 2012-08-14 23:02:30

回答

3

你幾乎回答了你自己的問題,mysql_insert_id()是你以後的功能:

// Add the user to the database: 
$q = "INSERT INTO database_name (column_2, column_3, column_4) VALUES ('$val1', '$val2', '$val3')"; 
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); 

if (mysqli_affected_rows($dbc) == 1) { // If it ran OK. 

    $_SESSION['column_1'] = mysqli_insert_id($dbc); 
    $_SESSION['column_2'] = $val1; 
    $_SESSION['column_3'] = $val2; 
    $_SESSION['column_4'] = $val3; 
+0

謝謝!我只是在你發佈它之前發現它。乾杯! – Jeremy 2012-08-14 23:06:02

+0

不僅在它自己的答案,它已被回答在過去:http://stackoverflow.com/a/10644509/367456 – hakre 2012-08-14 23:06:06

+0

@hakra,沒有已經回答的解決方案,我發現都使用LAST_INSERT_ID() 。 PHP手冊說$ mysqli-> insert_id是首選的解決方案,我不知道該把它放在哪裏。 – Jeremy 2012-08-14 23:09:13

相關問題