PDO lastInsertId返回0

时间:2016-12-12 15:03:28

标签: php pdo

我在PDO lastInsertId中持续获得0分。这是我的代码:

public static function createNewUser($email){

    $password = self::rand_string(6);

    $username = explode("@", $email);

    $username = $username[0];

    $passwordhashed = password_hash($password. self::salt(), PASSWORD_DEFAULT);

    $register = self::connect()->prepare("INSERT INTO `user`(email,username,password,password_salt,type)VALUES(?,?,?,?,?)");

    $register->execute(array($email,$username,$passwordhashed,$password,'customer'));

    $user_id = self::pdolastid();

    if($register){

        return $user_id;

    }
    else{

        return false;

    }

}

,最后一个插入id函数是:

public static function pdolastid(){

    $last = self::connect()->lastInsertId();

    return $last;

}

我已尝试使用pdolastid函数和self::connect()->lastInsertId()。 连接功能是:

public static function connect(){

    $servername = "localhost";

    $username = "root";

    $password = "";

    try {

        $conn = new \PDO("mysql:host=$servername;dbname=pw;port=3306;charset=utf8", $username, $password);

        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        return $conn;
    }
    catch(PDOException $e)
    {

        $con_error = "Connection failed: " . $e->getMessage();

        return $con_error;

    }

}

数据库将id作为主键并且是自动增量

有人请帮忙

0 个答案:

没有答案