PHP PDO :: lastInsertId返回0

时间:2018-03-27 18:22:36

标签: php pdo last-insert-id

我有类似的问题,你可以在其他问题中找到,但答案是不够的: this for example

在我的情况下,插入是正确的,但我没有设法获取ID。它总是返回0。 为什么?

的script.php

$src_db_conn = database_connection( SRC_DB_HOST , SRC_DB_NAME, SRC_DB_USERNAME, SRC_DB_PASSWORD );
$target_db_conn = database_connection( TARGET_DB_HOST , TARGET_DB_NAME, TARGET_DB_USERNAME, TARGET_DB_PASSWORD );

$sql_insert_terms = "SELECT nom_cat, slug FROM src_table ";
$result           = $src_db_conn->query($sql_insert_terms);

foreach ( $result as $row ){

    $f_wp_terms_row = array(
        'name' => $row['nom_cat'],
        'slug' => $row['slug']
    );

    $sql_insert_terms = "INSERT INTO target_table (name, slug) VALUES (:name, :slug)";
    $stmt = $target_db_conn->prepare( $sql_insert_terms );
    try {
        $target_db_conn->beginTransaction();
        $stmt->bindParam(":name", $f_wp_terms_row['name'], PDO::PARAM_STR);
        $stmt->bindParam(":slug", $f_wp_terms_row['slug'], PDO::PARAM_STR);
        $stmt->execute();
        print $target_db_conn->lastInsertId();
        $target_db_conn->commit();
    } catch(PDOExecption $e) {
        $target_db_conn->rollback();
        print "Error!: " . $e->getMessage() . "</br>";
    }

}

database_connection php功能

function database_connection( $host, $dbname, $username, $password ){
    try {
        $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully";
        return $conn;
    }
    catch(PDOException $e)
    {
        echo "Connection failed: " . $e->getMessage();
        return false;
    }
} 

target_table shema

Nom    Type         Attributs Extra NULL
foo_id bigint(20)   UNSIGNED  A_I   No
name   varchar(200)                 No 
slug   varchar(200)                 No 

1 个答案:

答案 0 :(得分:0)

我必须像这样绑定列id:

print $target_db_conn->lastInsertId("foo_id");