본문 바로가기

PHP/새로운문법

php insert_id 입력된 바로 그값의 PK(Primary Key)를 가져오는 명령

php insert_id


DB에 입력후 PK UID를 받아올때 사용.


2가지 방법이 있는데 mysql_insert_id() 과 last_insert_id() 입니다.

mysql_insert_id()은 PHP에서 처리해주는 명령문이고 last_insert_id()는 MySQL에서 처리해 주는 함수 입니다.

INSERT 명령으로 입력된 바로 그값의 PK(Primary Key)를 가져오는 명령을 수행합니다.



출처: http://jos39.tistory.com/191 [JOS39 블로그]



$no = $db->insert_id;




실시 예 (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";
    // use exec() because no results are returned
    $conn->exec($sql);
    $last_id = $conn->lastInsertId();
    echo "New record created successfully. Last inserted ID is: " . $last_id;
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>


http://www.w3im.com/ko/php/php_mysql_insert_lastid.html





$pdo->beginTransaction();

        $query = "INSERT INTO userMembers(mId,userId,userPw,userName,userHp,userEmail,userRegdate) VALUES(null,:userId,:userPw,:userName,:userHp,:userEmail,:userRegdate)";

        $stmt = $pdo->prepare($query);


        $stmt->bindValue(':userId', $_POST['userId'], PDO::PARAM_STR);

        $stmt->bindValue(':userPw', $_POST['userPw'], PDO::PARAM_STR);

        $stmt->bindValue(':userName', $_POST['userName'], PDO::PARAM_STR);

        $stmt->bindValue(':userHp', $_POST['userHp'], PDO::PARAM_STR);

        $stmt->bindValue(':userEmail', $_POST['userEmail'], PDO::PARAM_STR);

        $stmt->bindValue(':userRegdate', $userRegdate, PDO::PARAM_STR);

        $stmt->execute();

        $last_id = $pdo->lastInsertId();

        $pdo->commit();



'PHP > 새로운문법' 카테고리의 다른 글

현재 시간 입력  (0) 2017.11.14
PHP 절대경로  (0) 2017.11.14
배열, 연관배열 그리고 forEach  (0) 2017.11.11
예외처리(try ~ catch)  (0) 2017.11.09
간단한 로그인예제(Session)  (0) 2017.11.09