dpc57092
2018-04-02 03:56
浏览 388
已采纳

php PDO - 如何获取最后插入的ID?

i was trying to get parent_id which is the last_insert_id. I am using php PDO, i was trying to get lastinsertedId but it keeps gave me an error. I am able to execute parentRegister but i cannot get the lastInsertId using PDO. What's wrong on my code?

function connect() {
        // connection template
        // $pdo = new PDO('mysql:host=127.0.0.1;dbname=SocialNetwork;charset=utf8','root','');

        global $host;
        global $dbName;
        global $dbusername;
        global $dbpassword;

        try {
            $pdo = new PDO("mysql:host=".$host.";dbname=".$dbName."", $dbusername, $dbpassword);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     
            // $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // fetch as associative 
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); // fetch as object
            $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            return $pdo;

        } catch (PDOException $e) {
            // die('error  message: '.$e->message().'<br>');
            // die('Our system have some problems now. Please try again later');
            return false;
        }
    }

 function query($query, $params = array()) {

        $stmt = connect()->prepare($query);
        $stmt->execute($params);

        if(explode(' ', $query)[0] == 'SELECT'){
            $data = $stmt->fetchAll();
            return $data;     
        }
    }

            // parents 7 column
            $parentsData = array(
                'role_id'     => 2,
                'email'       => $submittedData['email'],
                'parent_name' => $submittedData['parentName'],
                'phone'       => $submittedData['phone'],
                'address'     => $submittedData['address'],
                'postcode'    => $submittedData['postcode'],
                'password'    => $submittedData['password']
            );

            // swimmers 6 column
            $swimmersData = array(
                'role_id'   => 3,
                'username'  => $submittedData['username'],
                'password'  => $submittedData['password'],
                'fname'     => $submittedData['fname'],
                'lname'     => $submittedData['lname'],
                'dob'       => $submittedData['dob']
            );

$parentsRegister    = query('INSERT INTO parents('.$parentsField.') VALUES ('.$parentsValue.')', $parentsData);
 $swimmersRegister   = query('INSERT INTO swimmers('.$swimmersField.',`parent_id`) VALUES ('.$swimmersValue.','.connect()->query("SELECT LAST_INSERT_ID()")->fetchColumn().')', $swimmersData);

I tried to use this code but keeps gave me 0

 $stmt = connect()->lastInsertId();
            echo $stmt;
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanrao3371 2018-04-02 04:59
    已采纳

    just figured out $pdo need to be set as global variable.

    // put pdo variable as global to handle last inserted id
    $pdo;
    
    function connect() {
            global $host;
            global $dbName;
            global $dbusername;
            global $dbpassword;
            global $pdo;
    
        try {
            $pdo = new PDO("mysql:host=".$host.";dbname=".$dbName."", $dbusername, $dbpassword);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     
            // $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // fetch as associative 
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); // fetch as object
            $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            return $pdo;
    
        } catch (PDOException $e) {
            // die('error  message: '.$e->message().'<br>');
            // die('Our system have some problems now. Please try again later');
            return false;
        }
    }
    
     function query($query, $params = array()) {
    
            $stmt = connect()->prepare($query);
            $stmt->execute($params);
    
            // if select
            if(explode(' ', $query)[0] == 'SELECT'){
                $data = $stmt->fetchAll();
                return $data;
    
            // otherwise (update, delete, insert)
            } else {
                return ($stmt) ? true : false;
            }
        }
    
      // insert to database
                $parentsRegister    = query('INSERT INTO parents('.$parentsField.') VALUES ('.$parentsValue.')', $parentsData);
                $swimmersRegister   = query('INSERT INTO swimmers('.$swimmersField.',`parent_id`) VALUES ('.$swimmersValue.','.$pdo->lastInsertId().')', $swimmersData);
    
    点赞 打赏 评论

相关推荐 更多相似问题