简体   繁体   中英

PHP PDO::lastInsertId returns 0

I have a similar problems that you can find in others questions, but answers were not sufficient : this for example

In my case the insert is right but I don't manage to get the ID. it returns 0 all the times. Why ?

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

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

我必须像这样绑定列ID:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM