Retrieving user id from one table and inserting it into another table - php

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.

Related

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

wrong resault in php

I tried to catch two variable ($phone,$key) and if $key exists in the random table from the first DB then check if &phone exists in users table in second DB return id else if doesn't exist make a row and then echo id. here is my code.where is my problem?
$Key = $_GET['key'];
$phone = $_GET['phone'];
$dublicate = "SELECT id,phone FROM users WHERE phone = $phone;";
$valid = "SELECT id,phone,random FROM random WHERE random = $Key;";
$verifyresult=mysqli_query($con,$valid);
$dublicateresult=mysqli_query($con2,$dublicate);
if($verifyresult == true )
{
if($dublicateresult == true){
$response=array();
while($row=mysqli_fetch_array($dublicateresult)){
array_push($response,array("id"=>$row[0],"phone"=>$row[1]));
echo $row[0];
}
}else{
$response=array();
while($row=mysqli_fetch_array($result)){
array_push($response,array("id"=>$row[0],"phone"=>$row[1],"random"=>$row[2]));
$result2 = mysqli_query($con2,"INSERT INTO users (phone)
VALUES ('$row[1]')");
$uniq = "SELECT id FROM users WHERE phone = $row[1];";
$result3=mysqli_query($con2,$uniq);
if($result3==true){
$response2=array();
while($row=mysqli_fetch_array($result3)){
array_push($response2,array("id"=>$row[0]));
echo $row[0];
}
}
}
}
}else echo "null";

How to set either profile name else user name in my php code

I want show my message system user Profile name(If have) else show user name.
In my every code I used as below, which work well.
if (empty($pname)) $pname = $username;
But in below I cannot understand how to Return 'profile name else user name' in my "function getusername($userid)".
Here if I use return $row[0] at my "function getusername" Its show username, But I want to show Profile name and If profile name empty then show user name.
Get profile name/user name code:
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
} else {
return "Unknown";
}
}
This code fetch a specific message
function getmessage($message) {
$sql = "SELECT * FROM mail WHERE `id` = '".$message."' && (`from` = '".$this->userid."' || `to` = '".$this->userid."') LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
// reset the array
$this->messages = array();
$row = mysql_fetch_assoc($result);
$this->messages[0]['id'] = $row['id'];
$this->messages[0]['title'] = $row['title'];
$this->messages[0]['message'] = $row['message'];
$this->messages[0]['from'] = $this->getusername($row['from']);
$this->messages[0]['to'] = $this->getusername($row['to']);
} else {
return false;
}
}
Use this
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $pname;
} else {
return "Unknown";
}
}
The problem is with how you are returning the value.
Change:
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
To:
if(empty($pname)) return $username;
else return $pname;
Also, it is suggested you use mysqli instead of mysql.
Can't you use something like this?
return isset($pname) ? $pname : $username;
This basically is: if $pname is set, then return $pname, else return $username

Records not inserting into mysql database

I am not getting any errors but the database does not get updated. Please render assistance. Here is my code.
<?php
ob_start();
include("dbinc.php");
$msg = "";
if($_SESSION['usertype'] != "admin"){
header("Location: index.php");
exit;
}
$pagetitle = "Sync Job Details";
include("header.php");
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
// $qpart = "";
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
if($_POST['allusers']!= "Y" && is_array($allowedusers)){
mysql_query("DELETE from accountusers WHERE accountid = '$accountid'");
foreach($allowedusers as $userid){
list($alljobs) = mysql_fetch_row(mysql_query("SELECT alljobs from users WHERE id= '$userid'"));
if($alljobs != "Y") {
mysql_query("INSERT into accountusers SET userid = '$userid' , accountid = '$accountid'");
}
}
}else{
mysql_query("DELETE from accountusers WHERE accountid = '$accountid'");
}
header("location: accountslist.php?done=1");
exit;
}
}
// if(isset($_GET['id'])){
// $record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
// foreach($record as $key=>$val) $record[$key] = stripslashes($val);
// }
if(isset($_GET['id'])){
$record = mysql_fetch_assoc(mysql_query("SELECT * from accounts WHERE id = '$_GET[id]'"));
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
}
// if($err ==1)
// {
// $record = $_POST;
// foreach($record as $key=>$val)
// $record[$key] = stripslashes($val);
// $msg ="Please fill the empty field";
// }
if( isset($err) && $err == 1 )
{
$record = $_POST;
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
if( isset($err) && $err == 2)
{
$msg = "The name has already been used.";
}
?>
I feel your frustration. If i could assist you i would. People in this forum are scared to answer you as they don't want to lose reputation points as the question was marked down to -4. I suggest do some more research and post your question eslewhere.

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
}
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.
}

Categories