I am implementing Google OAuth authentication in my PHP application, but the user profile data is not being inserted into my MySQL database. The authentication process works correctly, and I can retrieve the user data from Google, but the insertion into the database fails silently.
// init configuration
$clientID = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET';
$redirectUri = 'http://localhost/shop/home.php';
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
if (!isset($token['error'])) {
$client->setAccessToken($token['access_token']);
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$fname = $google_account_info->givenName;
$lname = $google_account_info->familyName;
$password = password_hash($google_account_info->id, PASSWORD_BCRYPT);
// check if user exists
$stmt = $conn->prepare("SELECT id, fname, lname, email FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// user exists
$user = $result->fetch_assoc();
$_SESSION['user_id'] = $user['id'];
$_SESSION['name'] = $user['fname'] . " " . $user['lname'];
$_SESSION['email'] = $user['email'];
} else {
// insert new user
$stmt = $conn->prepare("INSERT INTO users (fname, lname, email, mobile, password, status_status_id, gender_id)
VALUES (?, ?, ?, ?, ?, ?, ?)");
$mobile = "0712345678";
$status = 4;
$gender = 1;
$stmt->bind_param("ssssssi", $fname, $lname, $email, $mobile, $password, $status, $gender);
if ($stmt->execute()) {
$userId = $stmt->insert_id;
$_SESSION['user_id'] = $userId;
$_SESSION['name'] = $fname . " " . $lname;
$_SESSION['email'] = $email;
} else {
die("Insert failed: " . $stmt->error);
}
}
header("Location: home.php");
exit;
} else {
die("Error fetching token: " . $token['error']);
}
}
The OAuth flow completes successfully, and I can see that Google returns the user data correctly. However, when a new user tries to log in, the data is not inserted into the database. The script does not throw any errors, and it redirects to home.php, but the user record is not created.