Nitish Kumar Nitish Kumar - 7 months ago 15
SQL Question

Mysql error, passing two parameters in login page in php

I'm trying to build a session login with social login option via hybrid auth plugin. I'm having the following php code:

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"] = true;
$_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");
}

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

// if the used didn't authenticate using the selected provider before
// we create a new entry on database.users for him
if( ! $user_exist ) {
create_new_hybridauth_user(
$user_profile->email,
$user_profile->firstName,
$user_profile->lastName,
$provider_name,
$user_profile->identifier
);
}

// set the user as connected and redirect him
$_SESSION["user_connected"] = true;

header("Location: index.php");
}

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

global $link;

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


function mysqli_query_excute( $sql ) {
$server = 'localhost';
$user = 'root';
$password = '';
$db = 'nits_editor';

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

$result = mysqli_query( $link, $sql );

if( ! $result ) {
die( printf( "Error: %s\n", mysqli_error( $link ) ) );
}
return $result->fetch_object();
}

/*
* get the user data from database by email and password
**/
function get_user_by_email_and_password( $email, $password )
{
return mysqli_query_excute( "SELECT * FROM nits_user
WHERE user_email = '$email'
AND user_password = '$password'" );
}

/*
* 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 )
{
return mysqli_query_excute( "SELECT * FROM nits_user
WHERE hybridauth_provider_name = '$provider_name'
AND hybridauth_provider_uid = '$provider_user_id'" );
}

/*
* get the user data from database by provider name and provider user id
**/
function create_new_hybridauth_user( $email, $first_name, $last_name, $provider_name, $provider_user_id )
{
// let generate a random password for the user
$password = md5( str_shuffle( "0123456789abcdefghijklmnoABCDEFGHIJ" ) );

mysqli_query_excute(
"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()
)"
);
}


While executing the above, normal login is working perfectly fine but, while using social login I'm getting an error. I checked the whole code and came to know that
$sql
paramenter going inside the
mysqli_query
is getting two parameters, I mean user is being checked and selected from the database and also new user is bieng inserted into the database. I guess the
userexists
function throws true and false both. when i echoed the sql i got following code:

SELECT * FROM nits_user WHERE hybridauth_provider_name = 'facebook' AND hybridauth_provider_uid = '479196262278189'localhostrootnits_editorINSERT INTO nits_user ( user_email, user_password, user_firstname, user_lastname, hybridauth_provider_name, hybridauth_provider_uid, user_createdate ) VALUES ( 'nitishnoetic@gmail.com', 'f7bcca52ba33335000b15c58440588aa', 'Nitish', 'Kumar', facebook, 479196262278189, NOW() )


It is selecting and inserting both.

Please help me out with this.

Answer

try this

database connection only once.

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




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"] = true;
        $_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: success_page.php');
                 }
         }


        }
        else
        {

             // set the user as connected and redirect him

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



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

        }
    }




?>