gpt4 book ai didi

php - 如何从刚刚执行的MYSQL插入中获取主ID?

转载 作者:行者123 更新时间:2023-11-29 05:34:24 25 4
gpt4 key购买 nike

Possible Duplicate:
Select last insert id
Retrieving the last insert id from MySql using PHP
我正在尝试从正在执行的插入中获取唯一的id。在MySQL数据库中,列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;

...

最佳答案

你几乎回答了自己的问题,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;

关于php - 如何从刚刚执行的MYSQL插入中获取主ID? ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11962027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com