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

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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e
  • ¥15 使用deepspeed训练,发现想要训练的参数没有梯度
  • ¥15 寻找一块做为智能割草机的驱动板(标签-stm32|关键词-m3)
  • ¥15 信息管理系统的查找和排序
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),怎么用读取的电磁传感器信号表示小车所在的位置
  • ¥15 如何解决y_true和y_predict数据类型不匹配的问题(相关搜索:机器学习)
  • ¥15 PB中矩阵文本型数据的总计问题。