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;