使用insert_id获取自增id

3
我正在尝试在新用户注册时从我的“users”表中获取自动增量id,并能够在用户插入“users”表后立即将该id用于另一个查询。
我想在“payment_status”表中使用“users”表的“id”作为“user_id”。我正尝试使用“insert_id”函数的不同方法,但我无法将id转储到我的第一个查询中。即使此操作成功,我也不知道如何将其用于我所需的操作。请问有人可以提供一些指导如何做到这一点吗?
if($validation->passed()) {
            $user = new User();

            $salt = Hash::salt(32);

            try {
                $user->create(array(
                    'firstname' => Input::get('firstname'),
                    'lastname' => Input::get('lastname'),
                    'email' => Input::get('email'),
                    'phone_number' => Input::get('phone_number'),
                    'username' => Input::get('username'),
                    'password' => Hash::make(Input::get('password'), $salt),
                    'salt' => $salt,
                    'joined' => date('Y-m-d H:i:s'),
                    'group' => 1,
                    //var_dump($id->insert_id)
                    var_dump(mysqli::$insert_id)
                ));
                $success = "You have successfully created an account. We will notify you once the account has been approved. Then you will be able to login.";
                echo $success;


//Query to add user's name to payment_status db table

            if(isset($_POST['submit'])){
                $id = ( isset( $_SESSION['id'] ) ? $_SESSION['id'] : "" );
                $user_id = ( isset( $_SESSION['id'] ) ? $_SESSION['id'] : "" );
                $firstname = Input::get('firstname');
                $payment_name = "Owes";
                $payment_id = 1;
                $payment_amount = 0;



            $con = mysqli_connect("localhost","root","","db");
            /* check connection */
               if (mysqli_connect_errno()) {
                printf("Connect failed: %s\n", mysqli_connect_error());
                    exit();
                }
            $stmt = $con->prepare("INSERT INTO payment_status (id, user_id, firstname, payment_name, payment_id, payment_amount) VALUES (?, ?, ?, ?, ?, ?)");

                if ( false===$stmt ) {
              // Check Errors for prepare
              die(' Owes DB prepare() failed: ' . htmlspecialchars($con->error));
            }
            $stmt->bind_param('iissii', $id, $user_id, $firstname, $payment_name, $payment_id, $payment_amount);
                if ( false===$stmt ) {
                  // Check errors for binding parameters
                  die('Owes DB bind_param() failed: ' . htmlspecialchars($stmt->error));
                }
            $stmt->execute();

                if ( false===$stmt ) {
                  die('execute() failed: ' . htmlspecialchars($stmt->error));
                }
                // Debug
                var_dump($con->insert_id);

                // Output:
                // int(1)
            }

更新:添加了用户类

<?php
class User {
    private $_db,
            $_data,
            $_sessionName,
            $_cookieName,
            $_isLoggedIn;

    public function __construct($user = null) {
        $this->_db = DB::getInstance();

        $this->_sessionName = Config::get('session/session_name');
        $this->_cookieName = Config::get('remember/cookie_name');

        if(!$user) {
            if(Session::exists($this->_sessionName)) {
                $user = Session::get($this->_sessionName);

                if($this->find($user)) {
                    $this->_isLoggedIn = true;
                } else {
                    // process Logout
                }
            }
        } else {
            $this->find($user);
        }
    }

    public function update($fields = array(), $id = null) {

        if(!$id && $this->isLoggedIn()) {
            $id = $this->data()->id;
        }
        //echo $this->_db->update('users', $id, $fields);

        //if(!$this->_db->update('users', $id, $fields)) {
            //throw new Exception('There was a problem updating!');
        //}
        try {
            if(!$this->_db->update('users', $id, $fields)) {
                throw new Exception('There was a problem updating!');
            }
        }
           catch(Exception $e) {
        echo "An error occurred";
        throw $e;
    }
    finally {
                //This overrides the exception as if it were never thrown
        return "\nException erased";
    }
    try {
    echo asdf();
}
catch(Exception $e) {
    echo "\nResult: " . $e->getMessage();
}
         //if(!$this->_db->update('users', $id, $fields)) { 
        // throw new Exception('There was a problem updating!')->getMessage(); 
         //}
    }

    public function create($fields = array()) {


        if(!$this->_db->insert('users', $fields)) {
            throw new Exception('There was a problem creating an account:' .  $this->_db->errorMessage());

        }
    }

    public function find($user = null) {
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';
            $data = $this->_db->get('users', array($field, '=', $user));

            if($data->count()) {
                $this->_data = $data->first();
                return true;
            }
        }
        return false;
    }

    public function login($username = null, $password = null, $remember = false) {

        if(!$username && !$password && $this->exists()) {
            Session::put($this->_sessionName, $this->data()->id);
        } else {
            $user = $this->find($username);

            if($user) {
                if($this->data()->password === Hash::make($password, $this->data()->salt)) {
                    Session::put($this->_sessionName, $this->data()->id);

                    if($remember) {
                        $hash = Hash::unique();
                        $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

                        if(!$hashCheck->count()) {
                            $this->_db->insert('users_session', array(
                                'user_id' => $this->data()->id,
                                'hash' => $hash
                            ));
                        } else {
                            $hash = $hashCheck->first()->hash;
                        }

                        Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
                    }
                    return true;
                }
            }

        }
        return false;
    }

    public function hasPermission($key) {
        $group = $this->_db->get('groups', array('id', '=', $this->data()->group));

        if($group->count()) {
            $permissions = json_decode($group->first()->permissions, true);

            if($permissions[$key] == true) {
                return true;
            }
        }
        return false;
    }

    public function exists() {
        return (!empty($this->_data)) ? true : false;
    }

    public function logout() {

        $this->_db->delete('users_session', array('user_id', '=', $this->data()->id));

        Session::delete($this->_sessionName);
        Cookie::delete($this->_cookieName);
    }

    public function data() {
        return $this->_data;
    }
    public function isLoggedIn() {
        return $this->_isLoggedIn;
    }
}
?>

你可以在 $user->create() 方法的结尾返回最后插入的 id。然后在 try 语句中获取该值,例如 $lastId = $user->create(array(...))。 - mongjong
1个回答

6

在创建查询后,您应该使用mysqli::$insert_id

$user->create(array(
'firstname' => Input::get('firstname'),
'lastname' => Input::get('lastname'),
'email' => Input::get('email'),
'phone_number' => Input::get('phone_number'),
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'joined' => date('Y-m-d H:i:s'),
'group' => 1,                
));
var_dump(mysqli::$insert_id);

也许它将会是这样:
var_dump($user->insert_id);

1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Paul
1
第一个原因是因为您没有使用mysql类来创建用户,而第二个问题是,您使用的框架是什么? - Rox
我添加了我的用户类。 - Paul
1
请在插入后尝试 $user->id 或者如果不行的话 var_dump($user),而不是 var_dump($user->insert_id)。 - Rox
这是$user的转储... object(User)#6 (5) { ["_db":"User":private]=> object(DB)#3 (6) { ["_pdo":"DB":private]=> object(PDO)#4 (0) { } ["_query":"DB":private]=> object(PDOStatement)#7 (1) { ["queryString"]=> string(154) "INSERT INTO users (firstname, lastname, email, phone_number, username, password, salt, joined, group) Values (?, ?, ?, ?, ?, ?, ?, ?, ?)" } ["_error":"DB":private]=> bool(false) ["_results":"DB":private]=> array(0) { } ["_count":"DB":private]=> int(1) ["_errmsg":"DB":private]=> string(0) "" } - Paul
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接