3

我需要返回数据库中最后插入行的 id:

我有一个名为 DatabaseHandler 的类来使用 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;         
      }?>

和 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$$

当我这样调用时,会创建数据库记录,但 lastInsertId() 返回 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);

我做错了什么?

4

1 回答 1

0

尝试作为过程中的最后一个命令:

SELECT LAST_INSERT_ID();
于 2012-10-06T22:08:27.300 回答