Check to see if row exists - php
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
}
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.
}
Related
Retrieving user id from one table and inserting it into another table
Am working on a project where i got two tables 1. users table | (id is primary key) 2. movie table | (movie_id is primary key, id is foreign key) I want to get user_id from users table and want to insert movie related info when that user has logged in am using session_variables for this but i don't know if my code is correct or not i have tried following code but didn't get any result. This is my process.php $errors = []; $fav = ""; $rank = ""; $rewatched = ""; $status = ""; $recommend = ""; if (isset($_POST['submit'])) { if (empty($_POST['fav'])) { $errors['fav'] = 'Favourite required'; } if (empty($_POST['rank'])) { $errors['rank'] = 'Rank required'; } if (empty($_POST['rewatched'])) { $errors['rewatched'] = 'Rewatched required'; } if (isset($_POST['status'])) { $errors['status'] = 'Status required'; } if (isset($_POST['recommend'])) { $errors['recommend'] = 'Recommend required'; } $fav = $_POST['fav']; $rank = $_POST['rank']; $rewatched = $_POST['rewatched']; $status = $_POST['status']; $recommend = $_POST['recommend']; // Select id from users and insert into movie if (count($errors) === 0) { $sql = "SELECT * FROM movie WHERE id = (SELECT id FROM users WHERE id = '".$_SESSION['id']."')"; $query = "INSERT INTO movie SET fav=?, rank=?, rewatched=?, status=?, recommend=? WHERE id = '".$_SESSION['id']."'"; $stmt = $conn->prepare($query); $stmt->bind_param('siiss', $fav, $rank, $rewatched, $status, $recommend); $result = $stmt->execute(); if ($result) { $anime_id = $stmt->insert_id; $stmt->close(); $_SESSION['id'] = $movie_id; $_SESSION['fav'] = $fav; $_SESSION['rank'] = $rank; $_SESSION['rewatched'] = $rewatched; $_SESSION['status'] = $status; $_SESSION['recommend'] = $recommend; $_SESSION['message'] = 'Details have been submitted successfully!'; $_SESSION['type'] = 'alert-success'; } else { $_SESSION['error_msg'] = "Database error: Could not update details"; } } } In simple words i want to get id from users table and when that particular user has logged in and filled the form related to movie and submitted the results it should be stored in movie table with his/her user id. Thank you
<?php // Assuming $_SESSION['id'] is the User ID of the User Who Currently Logged in. $errors = []; $fav = ""; $rank = ""; $rewatched = ""; $status = ""; $recommend = ""; if (isset($_POST['submit'])) { if (empty($_POST['fav'])) { $errors['fav'] = 'Favourite required'; } if (empty($_POST['rank'])) { $errors['rank'] = 'Rank required'; } if (empty($_POST['rewatched'])) { $errors['rewatched'] = 'Rewatched required'; } if (isset($_POST['status'])) { $errors['status'] = 'Status required'; } if (isset($_POST['recommend'])) { $errors['recommend'] = 'Recommend required'; } $fav = $_POST['fav']; $rank = $_POST['rank']; $rewatched = $_POST['rewatched']; $status = $_POST['status']; $recommend = $_POST['recommend']; $id = $_SESSION['id']; // Insert into Movie Table if (count($errors) === 0) { $query = "INSERT INTO movie SET fav=?, rank=?, rewatched=?, status=?, recommend=?, id =?"; $stmt = $conn->prepare($query); $stmt->bind_param('siissi', $fav, $rank, $rewatched, $status, $recommend, $id); $result = $stmt->execute(); if ($result) { // If Insertion Successful } else { // If Something Went Wrong } } } In the above code, when the user submits the form it will capture the form details and store it in movie table with Foreign key as User Id. I assume that $_SESSION['id'] is the User Id of the currently Logged In User.
Display data for logged in user with same id from different table
I'm self-learning, so pardon my ignorance. I have 2 SQL tables: user and product, both tables contain "user_id" fields. I have successfully created a login system that uses email and password fields from the first table (user). I want to show specific information from the "product" table to the logged-in user. This information should be identified from the user_id field. (user with user_id of 1 should see the product with user_id of 1 login page has: <?php session_start(); $message = ""; require_once('account/pdoconnect.php'); if(isset($_POST["login"])) { if (empty($_POST["email"]) || empty($_POST["password"])) { $message = '<label>All fields are required</label>'; } else { $query = "SELECT * FROM user WHERE email = :email AND password = :password"; $statement = $pdotestconn->prepare($query); $statement->execute( array( 'email' => $_POST['email'], 'password' => $_POST['password'] ) ); $count = $statement->rowCount(); if($count > 0) { $_SESSION["email"] = $_POST["email"]; header("location:account/index.php"); } else { $message = '<label>Wrong Email or Password</label>'; } } } ?> Index page has: <?php session_start(); if(!isset($_SESSION["email"])) { header("location:../login.php"); exit; } ?> <?php include("pdoconnect.php"); $id = $_GET['user_id']; $result = $pdotestconn->prepare("SELECT * FROM product inner join user on user.user_id = product.user_id"); $result->execute(array($id)); $row = $result->fetch(PDO::FETCH_ASSOC); ?> Where I insert values with: <?php echo $row['amount']; ?> Problem: I get the same value in the first row (with user_id = 2) for every user logged in
First it's probably best to store the user id in the session, so in your first source... if($count > 0) { $row = $statement->fetch(PDO::FETCH_ASSOC); $_SESSION["email"] = $_POST["email"]; $_SESSION["userID"] = $row['ID']; // Make sure ID is the column name from the user table header("location:account/index.php"); } then to display the data, fetch the user ID from the session... $id = $_SESSION["userID"]; $result = $pdotestconn->prepare("SELECT * FROM product WHERE product.user_id =:id"); $result->execute(['id'=> $id]); $row = $result->fetch(PDO::FETCH_ASSOC); BTW you don't need to join to the user table if the user_id is in the product table
You don't have any parameter on your query. <?php include("pdoconnect.php"); $id = $_GET['user_id']; $result = $pdotestconn->prepare("SELECT * FROM product inner join user on user.user_id = product.user_id WHERE product.user_id =:id"); $result ->bindParam(':id', $id, PDO::PARAM_INT); $result ->execute(); $row = $result->fetch(PDO::FETCH_ASSOC); ?>
Returning inserted data data immediately after inserting into database
I have a function that checks if user data exists in database and returns email id of user. If it doesnt exits then it inserts and should return the inserted user email. Part of my function function checkUser($userdata){ $oauth_uid = $userdata->id; $email = $userdata->emailAddress; $check = $this->db->query("SELECT * FROM $this->userTable WHERE oauth_uid = '".$oauth_uid."' AND email = '".$email."'"); if(mysqli_num_rows($check) > 0){ $result = $check->fetch_array(MYSQLI_ASSOC); $query = "UPDATE $this->userTable SET fname = '".$userdata->firstName."', lname = '".$userdata->lastName."', email = '".$userdata->emailAddress."', location = '".$userdata->location->name."', country = '".$userdata->location->country->code."', picture_url = '".$userdata->pictureUrl."', profile_url = '".$userdata->publicProfileUrl."', modified = '".date("Y-m-d H:i:s")."' WHERE id = ".$result['id']; $this->db->query($query); return $result['id']; //this works it returns email of user if exists }else{ $query = "INSERT INTO $this->userTable(oauth_provider,oauth_uid,fname,lname,email,location,country,picture_url,profile_url,created,modified) VALUES('linkedin','".$userdata->id."','".$userdata->firstName."','".$userdata->lastName."','".$userdata->emailAddress."','".$userdata->location->name."','".$userdata->location->country->code."','".$userdata->pictureUrl."','".$userdata->publicProfileUrl."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."')"; $this->db->query($query); $id = $this->db->insert_id; $check = $this->db->query("SELECT * FROM $this->userTable WHERE oauth_uid = '".$id."'"); if(mysqli_num_rows($check) > 0){ $result = $check->fetch_array(MYSQLI_ASSOC); return $result['id']; //this doesnt work. It inserts the data into database but doesn't return anything. } } } The if statement works properly. It checks if user exists then returns the email. The else part works partially. It inserts the user into database but does not return the email how can i make this work. Thanks.
Your code says you want to return the user id and not the user email, if so Use return $check->insert_id; Instead of the if(mysqli_num_rows($check) > 0) block But if it is the user email you intend to get, then just return it from the userdata object return $userdata->emailAddress; Hope it helps
Duplicate Check of email field using php
i am new at php. i want to know that how i can add duplicate check on my email field. function email_exists($email){ global $db; $query = "SELECT email FROM student"; $statement = $db->prepare($query); $statement->execute(); $results = $statement->fetchAll(); foreach ($results as $key => $result) { if ($result['email'] == $email){ return true; } } return false; } i made this function and it works but i have a problem that when i update only name of my form.php and if the email remains same in the field it gives error. i want to know how i can solve this problem, if i only update name and not the email.
Try this query: $sql = "SELECT email, COUNT(*) AS count FROM student GROUP BY email HAVING count > 0 ORDER BY count DESC;";
Please try this : // #param email, id of updating record function email_exists($email, $id){ global $db; $query = "SELECT email FROM student WHERE id !=".$id; $statement = $db->prepare($query); $statement->execute(); $row_count = $statement->num_rows;// get total number of rows if($row_count > 0) { // record exists return true; } return false; }
function email_exists($email){ global $db; $query = "SELECT email FROM student WHERE email=:email"; $stmt = $db->prepare($query); $stmt->bindParam(":email", $email); $stmt->execute(); if ($stmt->rowCount() > 0) { return true; } else { return false; } }
How to INSERT and UPDATE
I've already checked here on stackoverflow and searched on google, but couldn't find my answer. I've created a rating system Thumbs up and down, only members could vote on a article. When a member votes, sql is updating the row voteup/votedown. Now I've made a new table called vote I've got there 5 columns id, user, uID, ctitle, cID So If a member who is logged in as for ex: Admin and he thumbs up the article for ex: I like coding SQL INSERT INTO the table which is called vote Admin to user the title into ctitle but at the same time he needs to update the table called post the row vote_up or vote_down I'm only receiving the error: Failed to vote, <?php include 'config.php'; require_once 'core/init.php'; $user = new User(); $username = $user->data()->username; function getAllVotes(mysqli $db, $id) { $votes = array(); if($q_13 = "SELECT * FROM post WHERE id = $id"); if($r_26 = $db->query($q_13)); if($r_26->num_rows==1) { $stem = $r_26->fetch_object(); $votes[0] = $stem->votes_up; $votes[1] = $stem->votes_down; } return $votes; } function getEffectiveVotes(mysqli $db, $id) { $votes = getAllVotes($db, $id); $effectiveVote = $votes[0] - $votes[1]; return $effectiveVote; } $id = $_POST['id']; $action = $_POST['action']; //current votes $cur_votes = getAllVotes($db, $id); //update votes if($action=='vote_up') { $votes_up = $cur_votes[0]+1; $q_13 = "UPDATE post SET votes_up = $votes_up WHERE id = $id"; $q_13 = "INSERT INTO vote WHERE user = '$username', cID = '$id'"; } elseif($action=='vote_down') { $votes_down = $cur_votes[1]+1; $q_13 = "UPDATE post SET votes_down = $votes_down WHERE id = $id"; $q_13 = "INSERT INTO vote WHERE user = '$username', cID = '$id'"; } $r_26 = $db->query($q_13); if($r_26) { $effectiveVote = getEffectiveVotes($db, $id); echo $effectiveVote." Archers"; } elseif(!$r_26) { echo "Failed to vote!"; } ?>