Nitish Kumar Nitish Kumar - 6 months ago 18
MySQL Question

Database not adding while having a social login in MySQL in php

I'm trying to build a

social media login
option in my login page with the help of
hybrid auth
plugin.

When the user clicks on login as facebook or any other social media plugin, I'm getting the logged in page or success page in which I'm trying to fetch data of the user and adding it to my own database in
MySql
, but it is not adding up. Following is my code:

<?php
include(dirname(__FILE__) . '/../nits-admin/version.php');

//database connection at top and also once only

global $link;
$server = 'localhost';
$user = 'root';
$password = '';
$db = 'nits_editor';

$link = mysqli_connect($server, $user, $password, $db);

if (!$link) {
die("Connection Failed!:" . mysqli_connect_error());
}


session_start();

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
header("location: index.php");
exit();
}

include(dirname(__FILE__) . '/../nits-db/db.php');

if (isset($_POST["user_email"]) && isset($_POST["password"])) {
$useremail = $_POST["user_email"];
$password = $_POST["password"];

$sql = "SELECT * FROM nits_user WHERE user_email ='$useremail' AND user_password ='$password'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($row = mysqli_fetch_array($sql)) {
$user_id = $row["user_id"];
}
$_SESSION["user_id"] = $user_id;
$_SESSION["loggedin"] = ture;
$_SESSION["user_email"] = $useremail;
$_SESSION["password"] = $password;
$_SESSION["user_name"] = $row["user_name"];
header("location: index.php");
exit();
} else {
echo 'Information incorrect';
}
} elseif (isset($_REQUEST["provider"])) {
//the selected provider
$provider_name = $_REQUEST["provider"];
try {
// inlcude HybridAuth library
// change the following paths if necessary
$config = dirname(__FILE__) . '/hybridauth/config.php';
require_once("hybridauth/Hybrid/Auth.php");

// initialize Hybrid_Auth class with the config file
$hybridauth = new Hybrid_Auth($config);

// try to authenticate with the selected provider
$adapter = $hybridauth->authenticate($provider_name);

// then grab the user profile
$user_profile = $adapter->getUserProfile();
}

// something went wrong?
catch (Exception $e) {
header("Location: login.php");
}

/*
* get the user data from database by provider name and provider user id
**/
function get_user_by_provider_and_id($provider_name, $provider_user_id, $link)
{
$qry1 = "SELECT * FROM nits_user WHERE hybridauth_provider_name = '$provider_name' AND hybridauth_provider_uid = '$provider_user_id'";

$result1 = mysqli_query($link, $qry1);

return mysqli_fetch_object($result1);


}



// check if the current user already have authenticated using this provider before
$user_exist = get_user_by_provider_and_id($provider_name, $user_profile->identifier, $link);

// if the used didn't authenticate using the selected provider before
// we create a new entry on database.users for him
if (!$user_exist) {



function create_new_hybridauth_user($email, $first_name, $last_name, $provider_name, $provider_user_id, $link)
{
// let generate a random password for the user
$password = md5(str_shuffle("0123456789abcdefghijklmnoABCDEFGHIJ"));

$qry2 = ("INSERT INTO nits_user
(
user_email,
user_password,
user_firstname,
user_lastname,
hybridauth_provider_name,
hybridauth_provider_uid,
user_createdate
)
VALUES
(
'$email',
'$password',
'$first_name',
'$last_name',
$provider_name,
$provider_user_id,
NOW()
);");


$result2 = mysqli_query($link, $qry2);



//$last_insert_id = mysqli_insert_id($link);


return $email;
}


$val = create_new_hybridauth_user($user_profile->email, $user_profile->firstName, $user_profile->lastName, $provider_name, $user_profile->identifier, $link);


if ($val) {

$_SESSION['loggedin'] = true;



if (isset($_SESSION['loggedin'])) {
header('Location: index.php');
}
}


} else {

// set the user as connected and redirect him

$_SESSION['loggedin'] = $user_profile->email;



if (isset($_SESSION['loggedin'])) {
header('Location: index.php');
}
header("Location: login.php");

}
}




?>


I'm not getting Database connection error, I mean connection is appropriate, as while logging in with username and password it matches with the database and redirects the defined page.
Don't be concern with the password, I'll be using
password_hash()
.
Please help me out!!!
Thanks

Answer

Try to debug your code as below

if (isset($_REQUEST["provider"])) {
    //the selected provider
    $provider_name = $_REQUEST["provider"];
    try {
        // inlcude HybridAuth library
        // change the following paths if necessary
        $config = dirname(__FILE__) . '/hybridauth/config.php';
        require_once("hybridauth/Hybrid/Auth.php");

        // initialize Hybrid_Auth class with the config file
        $hybridauth = new Hybrid_Auth($config);

        // try to authenticate with the selected provider
        $adapter = $hybridauth->authenticate($provider_name);

        // then grab the user profile
        $user_profile = $adapter->getUserProfile();
    }

    // something went wrong?
    catch (Exception $e) {
        header("Location: login.php");
    }

    /*
     * get the user data from database by provider name and provider user id
     * */

    function get_user_by_provider_and_id($provider_name, $provider_user_id, $link) {
        $qry1 = "SELECT * FROM nits_user WHERE hybridauth_provider_name = '".$provider_name."' AND hybridauth_provider_uid = '".$provider_user_id."'";

        $result1 = mysqli_query($link, $qry1);

        return mysqli_fetch_object($result1);
    }

    // check if the current user already have authenticated using this provider before
    $user_exist = get_user_by_provider_and_id($provider_name, $user_profile->identifier, $link);
    echo '<pre>'; print_r($user_exist);
    // if the used didn't authenticate using the selected provider before
    // we create a new entry on database.users for him
    if (!$user_exist) {



        function create_new_hybridauth_user($email, $first_name, $last_name, $provider_name, $provider_user_id, $link) {
            // let generate a random password for the user
            $password = md5(str_shuffle("0123456789abcdefghijklmnoABCDEFGHIJ"));

            $qry2 = ("INSERT INTO nits_user
                        (
                            user_email,
                            user_password,
                            user_firstname,
                            user_lastname,
                            hybridauth_provider_name,
                            hybridauth_provider_uid,
                            user_createdate
                        )
                        VALUES
                        (
                            '".$email."',
                            '".$password."',
                            '".$first_name."',
                            '".$last_name."',
                            '".$provider_name."',
                            '".$provider_user_id."',
                            NOW()
                        );");


            $result2 = mysqli_query($link, $qry2)or die(mysqli_error($link));


            $last_insert_id = mysqli_insert_id($link);
            echo 'lastinsertid:'.$last_insert_id;

            return $email;
        }

        $val = create_new_hybridauth_user($user_profile->email, $user_profile->firstName, $user_profile->lastName, $provider_name, $user_profile->identifier, $link);


        if ($val) {
            echo 'email:'.$val;
            $_SESSION['loggedin'] = true;



            if (isset($_SESSION['loggedin'])) {
                header('Location: index.php');
            }
        }
    } else {
        echo 'userexist:';
        // set the user as connected and redirect him

        $_SESSION['loggedin'] = $user_profile->email;



        if (isset($_SESSION['loggedin'])) {
            header('Location: index.php');
        }
        header("Location: login.php");
    }
}