2014-02-10 73 views
-1

我沒有插入任何值,但autocrement其中一列,我怎麼能得到最後插入的id值?返回最後插入自動遞增標識php

我用回聲mysql_insert_id();但我給了我'0'這似乎不正確。

+3

你能顯示更多的碼?順便說一句,'mysql_ *'函數已被棄用;改爲使用PDO或MySQLi。 – Raptor

+0

我認爲你誤解了它返回的內容,如果你有一個int類型的列自動增量,並且你插入一條新記錄,你可以得到最後插入的id。但是,如果您在某個列字段更新給定的行,那麼它將不會給您最後插入的ID。 – Prix

+0

最後一個ID僅在'INSERT'後可用。遞增一個值(即使用'UPDATE')不會返回一個ID。 –

回答

0

mysql_insert_id()僅在將數據插入到表中時才起作用。

+0

我插入了數據 – user3277912

+0

它將僅返回主鍵字段的下一個值 –

0
  1. 數據庫

    CREATE TABLE MyGuests( ID INT(6)UNSIGNED AUTO_INCREMENT PRIMARY KEY, 姓名VARCHAR(30)NOT NULL, 姓氏VARCHAR(30)NOT NULL, 電子郵件VARCHAR(50 ), reg_date TIMESTAMP ) 最後插入的ID:


  1. 實施例(mysqli的面向對象)

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

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql = "INSERT INTO MyGuests (firstname, lastname, email) 
VALUES ('John', 'Doe', '[email protected]')"; 

if ($conn->query($sql) === TRUE) { 
    $last_id = $conn->insert_id; 
    echo "New record created successfully. Last inserted ID is: " . $last_id; 
} else { 
    echo "Error: " . $sql . "<br>" . $conn->error; 
} 

$conn->close(); 
?> 

  • 實施例(庫MySQLi程序)

  • <?php 
    $servername = "localhost"; 
    $username = "username"; 
    $password = "password"; 
    $dbname = "myDB"; 
    
    // Create connection 
    $conn = mysqli_connect($servername, $username, $password, $dbname); 
    // Check connection 
    if (!$conn) { 
        die("Connection failed: " . mysqli_connect_error()); 
    } 
    
    $sql = "INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES ('John', 'Doe', '[email protected]')"; 
    
    if (mysqli_query($conn, $sql)) { 
        $last_id = mysqli_insert_id($conn); 
        echo "New record created successfully. Last inserted ID is: " . $last_id; 
    } else { 
        echo "Error: " . $sql . "<br>" . mysqli_error($conn); 
    } 
    
    mysqli_close($conn); 
    ?> 
    

    1. 實施例(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', '[email protected]')"; 
        // 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; 
    ?>