[mysql] LAST_INSERT_ID() > DB/SQLite

본문 바로가기
사이트 내 전체검색

DB/SQLite

[mysql] LAST_INSERT_ID()

페이지 정보

작성자 sbLAB 댓글 0건 조회 6,996회 작성일 18-07-25 17:11

본문

http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

 

Mysql 은 대부분의 경우 자동증가필드( AUTO_INCREMENT) 가 필수 다.

만약 어떤 대상자 정보가 삽입(INSERT)된 다음 그 자동증가 ID값으로 어떤 작업을 하고자 한다면..

mysql 엔진이 특별히 알려주는 방법외에는 다른방법이 없다. 

 

데이타 INSERT 와 동시에 유일한 자동증가값(ID)이 생성되는데, 이 유일한 ID값으로 업로드될 파일명이

정해져야 한다고 생각해보자. 이런일은 종종 있는 일이다.

 

이때는 인서트 작업후 바로 이어서 SELECT LAST_INSERT_ID() 쿼리를 날리면 현재 동일한 커넥션에서

이루어지고 있는 같은 선상의 삽입된 ID값을 알려주게 되고, 이 ID값을 파일명으로 정하면 된다.

 

 그렇다면 PHP에서 SELECT LAST_INSERT_ID()  쿼리를 직접 날려 줘야하는 걸까? 

 

<?
$link = @mysql_connect('localhost', 'user', 'pw');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('test',$link);

$sqlstr="INSERT INTO `idtable` (`name`) VALUES ('검은별')";

mysql_query($sqlstr);

$result=mysql_query("SELECT LAST_INSERT_ID() AS ID");
echo mysql_result($result,0,"ID");

mysql_close($link);
?>  

 

4cb3f0ba517befeb9b243ed5915443ee_1532506275_6331.jpg
 


그럴필요가 없다.  PHP는 이미 MYSQL의  LAST_INSERT_ID()  쿼리를 날리는 mysql_insert_id()  API를 갖고 있다.

 

 <?
$link @mysql_connect('localhost''user''pw');
if (!$link) {    die('Could not connect: ' . mysql_error()); }
mysql_select_db('test',$link);

$sqlstr="INSERT INTO `idtable` (`name`) VALUES ('검은별')";
mysql_query($sqlstr);


echo mysql_insert_id();

mysql_close($link);
?>  

  

http://php.net/manual/en/function.mysql-insert-id.php 

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------

Table 12.17. Information Functions

Name

Description
BENCHMARK()Repeatedly execute an expression
CHARSET()Return the character set of the argument
COERCIBILITY()Return the collation coercibility value of the string argument
COLLATION()Return the collation of the string argument
CONNECTION_ID()Return the connection ID (thread ID) for the connection
CURRENT_USER()CURRENT_USERThe authenticated user name and host name
DATABASE()Return the default (current) database name
FOUND_ROWS()For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause
LAST_INSERT_ID()Value of the AUTOINCREMENT column for the last INSERT
ROW_COUNT()The number of rows updated
SCHEMA()A synonym for DATABASE()
SESSION_USER()Synonym for USER()
SYSTEM_USER()Synonym for USER()
USER()The user name and host name provided by the client
VERSION()Returns a string that indicates the MySQL server version


댓글목록

등록된 댓글이 없습니다.

회원로그인

접속자집계

오늘
118
어제
417
최대
1,279
전체
220,889

그누보드5
Copyright © sebom.com All rights reserved.