2012-08-14 50 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

相关问题