Programing

PHP에서 MySQL 테이블의 마지막으로 삽입 된 ID를 얻으려면 어떻게해야합니까?

lottogame 2020. 9. 8. 21:54
반응형

PHP에서 MySQL 테이블의 마지막으로 삽입 된 ID를 얻으려면 어떻게해야합니까?


새 데이터가 자주 삽입되는 테이블이 있습니다. 테이블의 마지막 ID를 가져와야합니다. 어떻게 할 수 있습니까?

유사 SELECT MAX(id) FROM table합니까?


PDO를 사용하는 경우 PDO::lastInsertId.

Mysqli를 사용하는 경우 mysqli::$insert_id.

여전히 Mysql을 사용하는 경우 :

mysql_*새 코드에서 함수를 사용하지 마십시오 . 더 이상 유지 되지 않으며 공식적으로 사용되지 않습니다 . 참고 항목 빨간색 상자 ? 에 대해 알아 준비된 문 대신 사용할 PDO 또는 MySQLi를 - 이 기사는 당신이 어떤을 결정하는 데 도움이됩니다. PDO를 선택한 경우 여기에 좋은 자습서가 있습니다.

그러나 필요한 경우 mysql_insert_id.


현재 연결에 삽입 된 마지막 ID가 무엇인지 아는 기능이 있습니다.

mysql_query('INSERT INTO FOO(a) VALUES(\'b\')');
$id = mysql_insert_id();

또한 max를 사용 하는 것은 두 개의 다른 세션에서 코드를 동시에 사용하면 문제발생할 수 있기 때문에 나쁜 생각 입니다.

이 함수를 mysql_insert_id 라고합니다.


괜찮아. 또한 LAST_INSERT_ID ()를 사용할 수 있습니다.


PDO :

$pdo->lastInsertId();

Mysqli :

$mysqli->insert_id;

mysql_*새 코드에서 함수를 사용하지 마십시오 . 더 이상 유지 되지 않으며 공식적으로 사용되지 않습니다 . 참고 항목 빨간색 상자 ? 에 대해 알아 준비된 문 대신 사용할 PDO 또는 MySQLi를 - 이 기사는 당신이 어떤을 결정하는 데 도움이됩니다. PDO를 선택한 경우 여기에 좋은 자습서가 있습니다.


mysql_insert_id () 함수를 사용하십시오 .

여기에서 비슷한 질문보기


당신이 쓴 내용은 id그들이 독특하고 자동으로 증가한다고 가정 하면 가장 큰 결과를 얻을 수 있으며 동시성 문제를 초대해도 괜찮을 것입니다.
MySQL을 데이터베이스로 사용하고 있기 때문에 LAST_INSERT_ID()삽입을 수행 한 현재 연결에서만 작동 하는 특정 기능 이 있습니다.
PHP는 mysql_insert_id.


내장 된 PHP 기능으로 최근 삽입 된 ID를 얻을 수 있습니다. mysql_insert_id();

$id = mysql_insert_id();

당신은 또한 최신 ID를 얻을

$id = last_insert_id();

Codeigniter에서 마지막으로 삽입 된 ID를 얻으려면 삽입 쿼리를 실행 한 후 insert_id()데이터베이스에서 호출 하나의 함수 만 사용 하면 마지막으로 삽입 된 ID를 반환합니다.

전의:

$this->db->insert('mytable',$data);
echo $this->db->insert_id(); //returns last inserted id

한 줄로

echo $this->db->insert('mytable',$data)->insert_id();

을 사용하는 것은 괜찮지 만 사용 mysql_insert_id()에 대한 특정 참고 사항이 하나 있습니다. INSERT 쿼리를 실행 한 후 호출해야합니다. 즉, 동일한 스크립트 세션에서 의미합니다. 그렇지 않으면 올바르게 작동하지 않습니다.


이것이 잘 작동합니다.

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "INSERT blah blah blah...";
$result = mysqli_query($link, $query);

echo mysqli_insert_id($link);

참고 : 하나의 문으로 여러 삽입을 수행하면 mysqli :: insert_id가 올바르지 않습니다.

탁자:

create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));

이제 다음을 수행하십시오.

insert into xyz (name) values('one'),('two'),('three');

mysqli :: insert_id는 3이 아닌 1이됩니다.

올바른 값을 얻으려면 다음을 수행하십시오.

mysqli::insert_id + mysqli::affected_rows) - 1

이것은 문서이지만 약간 모호합니다.


원하는 테이블의 마지막 auto_increment ID를 얻기 위해 순수한 MySQL 구문을 사용하는 것을 선호합니다.

php mysql_insert_id () 및 mysql last_insert_id ()는 마지막 트랜잭션 ID 만 제공합니다.

스키마에있는 테이블의 마지막 auto_incremented ID (마지막 트랜잭션 1뿐만 아니라)를 원하는 경우이 쿼리를 사용할 수 있습니다.

SELECT AUTO_INCREMENT FROM information_schema.TABLES
    WHERE TABLE_SCHEMA = 'my_database' 
    AND TABLE_NAME = 'my_table_name';

그게 다야.


예를 들어 답을 보지 못하는 것이 슬프다.

Using Mysqli::$insert_id:

$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$mysqli->query($sql);
$last_inserted_id=$mysqli->insert_id; // returns last ID

Using PDO::lastInsertId:

$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$database->query($sql);
$last_inserted_id=$database->lastInsertId(); // returns last ID

Clean and Simple -

$selectquery="SELECT id FROM tableName ORDER BY id DESC LIMIT 1";
$result = $mysqli->query($selectquery);
$row = $result->fetch_assoc();
echo $row['id'];

Using MySQLi transaction I sometimes wasn't able to get mysqli::$insert_id, because it returned 0. Especially if I was using stored procedures, that executing INSERTs. So there is another way within transaction:

<?php

function getInsertId(mysqli &$instance, $enforceQuery = false){
    if(!$enforceQuery)return $instance->insert_id;

    $result = $instance->query('SELECT LAST_INSERT_ID();');

    if($instance->errno)return false;

    list($buffer) = $result->fetch_row();

    $result->free();

    unset($result);

    return $buffer;
}

?>

Use mysqli as mysql is depricating

<?php
$mysqli = new mysqli("localhost", "yourUsername", "yourPassword", "yourDB");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
// Conside employee table with id,name,designation
$query = "INSERT INTO myCity VALUES (NULL, 'Ram', 'Developer')";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

/* close connection */
$mysqli->close();
?>

I tried

mysqli_insert_id($dbConnectionObj)

This returns the current connection's last inserted id so if you are managing your connections properly this should work. Worked for me at least.


Please use PDP and then try this

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

$lastid = mysql_insert_id();


By all this discussion I assume that the reason to check max id is to know what id should be next.. (if my max id is 5 then next will be 5+1=6).

>>If this is not the reason, my best apologies

Case if someone else INSERTs information between your CHECK and INSERT would give you wrong ID.

So It can be solved if you would create hash that could include timestamp or other unique value.

Then in the same function you can insert your information with empty values and your hash. That would create ID if you have AUTO_INCRECEMENT selected.

Then in the same function you would still have your hash and you could look for id with the same hash. And then you could complete populating empty values with mysql UPDATE.

This includes a bit more connections, but it is still a way to do it...

Good luck solving it.


If your table have AUTO INCREMENT column like UserID,Emp_ID,.. then you can use this query to get last inserted record SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name) In PHP code:

$con = mysqli_connect('localhost', 'userid', 'password', 'database_name');
                                if (!$con) {
                                    die('Could not connect: ' . mysqli_error($con));
                                }
                                $sql = "SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)";
                                $result = mysqli_query($con, $sql);

Then you can use fetched data as your requirement


mysql_query("INSERT INTO mytable (product) values ('kossu')");

printf("Last inserted record has id %d\n", ***mysql_insert_id()***);

참고URL : https://stackoverflow.com/questions/1685860/how-do-i-get-the-last-inserted-id-of-a-mysql-table-in-php

반응형