why pdo->lastInsertId() return 0 when i call STORED PROCEDURE in mysql?

一个人想着一个人 提交于 2019-12-07 16:03:43

问题


i need return id of last inseted row in my database :

i have a class named DatabaseHandler to use pdo

    <?php class DatabaseHandler
    {
      private static $_mHandler;

      private function __construct()
      {}

      private static function GetHandler()
      {
        if (!isset(self::$_mHandler))
        {
          try
          {
            self::$_mHandler =
              new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD,
                      array(PDO::ATTR_PERSISTENT => DB_PERSISTENCY));
            self::$_mHandler->setAttribute(PDO::ATTR_ERRMODE,
                                           PDO::ERRMODE_EXCEPTION);
            self::$_mHandler->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
          }
          catch (PDOException $e)
          {
            self::Close();
            trigger_error($e->getMessage(), E_USER_ERROR);
          }
        }
        return self::$_mHandler;
      }

      public static function Close()
      {
        self::$_mHandler = null;
      }
      public static function Execute($sqlQuery, $params = null)
      {
        try
        {
          $database_handler = self::GetHandler();
          $statement_handler = $database_handler->prepare('set names utf8; ' . $sqlQuery);
          $statement_handler->execute($params);
          $result=$database_handler->lastInsertId();              
        }catch(PDOException $e){
          self::Close();
          trigger_error($e->getMessage(), E_USER_ERROR);
        }
        return $result;         
      }?>

and STORED PROCEDURE in mysql db :

 CREATE PROCEDURE `sp_users_Insert`(IN _username VARCHAR(50), IN _email VARCHAR(50), IN _password CHAR(32), IN _ip VARCHAR(15), IN _reg_date INT,  IN _ref_id MEDIUMINT)
    BEGIN
       INSERT INTO n_users
       (username , email , password , ip , reg_date , ref_id )
             VALUES(_username , _email , _password , _ip , _reg_date , _ref_id );
    END$$

and when i call that like this , the database record is created but lastInsertId() return 0:

$username =me;
$email=me@me.com;
$password =msadss;
$ip =12.0.0.1;
$reg_date =1347284764;
$ref_id =12;

$sql = 'CALL `sp_users_Insert`(:username,:email,:password,:ip,:reg_date,:ref_id)';
$params = array (':username' => $username, ':email' => $email, ':password' => $password, ':ip' => $ip, ':reg_date' => $reg_date, ':ref_id' => $ref_id);
DatabaseHandler::Close(); 
return DatabaseHandler::Execute($sql, $params);

What i am doing wrong?


回答1:


Try as last command in your procedure:

SELECT LAST_INSERT_ID();


来源:https://stackoverflow.com/questions/12764222/why-pdo-lastinsertid-return-0-when-i-call-stored-procedure-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!