Colin Roe
Colin Roe

Reputation: 804

Check to see if row exists

I have a form and when submitted, data will be inserted into three tables (user, journey, user_journey tables). Before the data is inserted, I want to check if that user already exists in the user table. If not, then there is no problem, the user will be inserted into the user table, however, if the user already exists in the user table, I don't want to add the user again. I want to get the user's user_id and insert into the third table (user_journey).

At the moment, when I submit the form, the user is inserted into the user table even if they exist in the table already.

I'm not sure about the way I went about checking if the user exists is correct and the way I'm fetching the user_id. Any advice would be appreciated

$query = $db->query("SELECT COUNT(*) FROM user WHERE facebook_id = '.$hdnFacebookId.'");

        //$query->execute();
        //$countRows = $query->rowCount();//return number of rows
        //check to see if user is already in the database

        if  ($query->fetchColumn() > 0)
        {
            if ($oneWay)
            {
                $query_journey = $db->prepare("INSERT INTO journey
                (from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
                VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')");
            }
            else
            {
                $query_journey = $db->prepare("INSERT INTO journey
                (from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
                VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')");
            }
            $user_query = $db->prepare("SELECT user_id FROM user WHERE facebook_id = '$hdnFacebookId'");
            $result = $user_query->execute();
            $user_query_result = $user_query->fetch(PDO::FETCH_ASSOC);

            $query_journey->execute();//EXECUTE QUERY

            $lastJourneyID = $db->lastInsertId();
            $queryUserJourney = $db->prepare("INSERT INTO user_journey
                                (journey_id,user_id)
                                VALUES('$lastJourneyID','$user_query_result')");
            $queryUserJourney->execute();//EXECUTE QUERY

            //include('index.php');
        }
        else //insert user
        {
            //if $oneWay true, then omit $returnDate and $returnTime
            if ($oneWay)
            {
                $query = $db->prepare("INSERT INTO journey
                (from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
                VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')");
            }
            else
            {
                $query = $db->prepare("INSERT INTO journey
                (from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
                VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')");
            }
            $queryfb = $db->prepare("INSERT INTO user
                (facebook_id,facebook_username,facebook_first_name,facebook_last_name,facebook_image,facebook_link)
                VALUES('$hdnFacebookId','$hdnUsername','$hdnFirstName','$hdnLastName','$hdnFacebookImg','$hdnFacebookUrl')");

            $query->execute();
            $lastUserID = $db->lastInsertId();
            $queryfb->execute();
            $lastJourneyID = $db->lastInsertId();
            $queryUserJourney = $db->prepare("INSERT INTO user_journey
                                (user_id,journey_id)
                                VALUES('$lastJourneyID','$lastUserID')");
            $queryUserJourney->execute();

        }

UPDATED

function userExists($db, $hdnFacebookId)
        {
            $userQuery = "SELECT * FROM user WHERE facebook_id = :user;";
            $stmt = $db->prepare($userQuery);
            $stmt->execute(array(':user'=>$hdnFacebookId));
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            if($result)
            {
                return true;
            }
            return false;
        }

        $userExists = userExists($db,$hdnFacebookId);
        if($userExists)
        {
            //don't insert user
            //get user's id from database
            $user_query = $db->prepare("SELECT * FROM user WHERE facebook_id = '$hdnFacebookId'");
            $result = $user_query->execute();
            $user_query_result = $user_query->fetch(PDO::FETCH_ASSOC);
            $userID = $user_query_result['user_id'];
            $query_journey->execute();//EXECUTE QUERY
            $lastJourneyID = $db->lastInsertId();
            $queryUserJourney = $db->prepare("INSERT INTO user_journey
                                (journey_id,user_id)
                                VALUES('$lastJourneyID','$userID')");
            $queryUserJourney->execute();//EXECUTE QUERY
        }
        else
        {
            //insert user
        }

Upvotes: 0

Views: 522

Answers (1)

Jonast92
Jonast92

Reputation: 4967

A typical "Check if user exists":

function userExists($db, $user)
{
    $userQuery = "SELECT * FROM users u WHERE u.user=:user;";
    $stmt = $db->prepare($userQuery);
    $stmt->execute(array(':user' => $user));
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if($result)
    {
         return true;
    }
    return false;
}

So you can do something like

$user = isset($_POST['user']) ? $_POST['user'] : "Unknown";
$userExists = userExists($db, $user);
if($userExists)
{
    // Don't insert
]
else
{
    // Insert the user.
}

Upvotes: 3

Related Questions