PDO :: last Insert Id始终返回0使用MYSQL并准备语句

时间:2015-11-05 08:04:08

标签: php mysql pdo

我无法从pdo连接获取最后一个插入ID,它总是返回0.我没有解决方案请帮助我。 我的函数getConnection();

function getConnection(){
$servername="localhost";
$username="mmjadmin";
$password="gfam";
try{
    $conn = new PDO("mysql:host=$servername;dbname=mmjdb",$username,$password);
    $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    return $conn; 
}catch(PDOException $e){
    echo "Connect to database fail " . $e->getMessage();
}}

我将此函数调用于其他函数以将数据插入

function insertUser($username,$password){
    $sql = "INSERT INTO T_Users(
                    username,
                    password,
                    regist_date,
                    update_date)
                VALUES(
                    :username,
                    :password,
                    CURRENT_TIMESTAMP,
                    CURRENT_TIMESTAMP)";
    $stmt = getConnection()->prepare($sql);
    $stmt->bindParam(':username',$username);
    $stmt->bindParam(':password',$password);
    $stmt->execute();
    $userid = getConnection()->lastInsertId();
}

我无法获取插入的最后一个用户标识,即用户标识是自动增量,它总是返回0.

1 个答案:

答案 0 :(得分:5)

当您拨打getConnection()时,您也会创建一个新连接。您应该存储连接并重新使用它:

function insertUser($username,$password){
    $conn = getConnection();
    $sql = "INSERT INTO T_Users(
                    username,
                    password,
                    regist_date,
                    update_date)
                VALUES(
                    :username,
                    :password,
                    CURRENT_TIMESTAMP,
                    CURRENT_TIMESTAMP)";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':username',$username);
    $stmt->bindParam(':password',$password);
    $stmt->execute();
    $userid = $conn->lastInsertId();

    return $userId; // if needed
}