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

时间:2018-04-02 03:56:21

标签: php pdo

我试图获取parent_id,这是last_insert_id。我正在使用php PDO,我试图获得lastinsertedId,但它一直给我一个错误。 我能够执行parentRegister,但我无法使用PDO获取lastInsertId。 我的代码有什么问题?

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);

我尝试使用此代码,但一直给我0

 $stmt = connect()->lastInsertId();
            echo $stmt;

1 个答案:

答案 0 :(得分:0)

刚想出$ pdo需要设置为全局变量。

// 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);