How to insert primary key second table - php

I'm retrieving data from single html form and inserting it into two different SQL table USER and PAYMENT_DETAILS, I made a foreign key in PAYMENT_DETAILS table, now I'm confused how to add a primary key of USER table into the PAYMENT_DETAILS table
if (isset($_POST['submit']))
{
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$gender=$_POST['gender'];
$datofbirth=$_POST['dateofbirth'];
$primary_email=$_POST['primary_email'];
$Email_Confirm=$_POST['Email_Confirm'];
$phone=$_POST['contact'];
$password=$_POST['password'];
$confirmpassword=$_POST['confirmpassword'];
$username= $_POST['username'];
$status=2;
//payment information
$ownername=$_POST['ownername'];
$cvvnumber=$_POST['cvvnumber'];
$cardnumber=$_POST['cardnumber'];
$cardtype=$_POST['cardtype'];
$expirydate=$_POST['expirydate'];
$balance=$_POST['money'];
$mysql_get_users = mysql_query("SELECT * FROM user where username='$username'");
$get_rows = mysql_affected_rows($conn);
if($get_rows >=1)
{
echo "user exists";die();
}
else
{
$query1= mysql_query("
INSERT INTO
user
(firstname,lastname,gender,datofbirth,primary_email,contact,password,username,status)
VALUES
('$firstname','$lastname','$gender','$datofbirth','$primary_email','$phone','$password','$username','$status')");
$query2 = mysql_query("
INSERT INTO
payment_details
(Owner_Name,CVV_Numer,Card_Number,Card_Balance,Card_Type,Validation)
VALUES
('$ownername','$cvvnumber','$cardnumber','$balance','$cardtype','$expirydate')");

that php function gives the last entered record's primary key.(put the function after the first query. that means, it will give first entered primary key.)
mysql_insert_id();

Related

Set every username can choose the items in spinner one time

My case now is every username can select the items in spinner one time only. Mean if the spinner has 5 item, the user can choose all of them but all of them just can one time only. Below are my select data php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
//Creating an sql query
$sql = "INSERT INTO Selection (username, name) VALUES
('$username','$name')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Select Successfully';
}else{
echo 'Sorry, You Already Select it Before';
}
//Closing the database
mysqli_close($con);
}
The name in this php means the item in spinner. I am no idea how to set every username can select all the item in spinner one time only. I am using localhost phpmyadmin.
You can specify unique constraint for username and name columns.
Alter the Selection table using this code:
ALTER TABLE `Selection` ADD UNIQUE `unique_index`(`username`, `name`);
Now if you try to insert any username and name pair that is already inserted, will fail.
Why are you not testing if the entry is already on database before you do insert? May be this (Untested) code might help:
if($_SERVER['REQUEST_METHOD']=='POST')
{
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
//Importing our db connection script
require_once('dbConnect.php');
//Creating an sql query
$check_sql = "SELECT * FROM Selection WHERE username='$username' AND name='$name' LIMIT 1";
$check_res = $mysqli->query($con,$check_sql);
if($check_res && mysqli_num_rows($check_res) >0)
{
echo 'Sorry, You Already Select it Before';
}
else
{
$sql = "INSERT INTO Selection (username, name) VALUES ('$username','$name')";
if(mysqli_query($con,$sql))
{
echo 'Select Successfully';
}
else
{
echo "Select failed for some other reason";
}
}
//Closing the database
mysqli_close($con);
}
I think for checking the user to spin it only once only you need to add a flag in your database structure such as
u_id | flag |
--------------
1 | 1
--------------
So that when retrieving or fetching or you can say while checking you just have to make sure that this particular u_id has already spin it once so further it can't be allowed.
So before inserting check the username or user_id of particular.
$sql = "SELECT u_id from user_spins table where u_id = 1 AND flag = 1";
//if yes then don't allow to proceed
//if no then insert into User_spins table
$sql = "INSERT INTO User_spins (u_id, name,flag) VALUES
('$username','$name',1)";
//Importing our db connection script
require_once('dbConnect.php');

SQL Select/ Insert / Update query PHP MySQL

I have a table with columns userID(int),timeIN(date),timeOUT(date)
I am inserting a record in mysql database. First I check if the userID is correct from the other table and if its correct it will add a new record of the userID and timeIN(date) whereas the timeOUT will be NULL, else it will display error if the userID is not correct. I want my code to be able to check if the user is currently timeIN so it will prevent a double entry. I would also like to insert or update timeOUT(date) if the values of userID is equals to the user input and timeIN is not null and timeOUT is null.
Please kindly help...thanks.
Here is my code for inserting userID and timeIN: IT WORKS when inserting into mysql database.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
require_once('dbConnect.php');
$userID = $_POST['userID'];
$sql = "SELECT * FROM employee WHERE userID='$userID'";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check)){
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
echo 'Time IN Successful!';
}else{
echo 'Invalid USER ID. Please try again!';
}
mysqli_close($con);
}
?>
You should handle these checks inside the database. The current check you are doing in the database can be handled by a foreign key constraint:
alter table dtr add constraint fk_dtr_userId
foreign key (userId) references employee(userId);
The second means that you want only one row with a NULl value. Ideally, this could be handled with a unique constraint:
alter table dtr add constraint unq_dtr_userId_timeOut
unique (userId, timeOut);
Unfortunately (for this case), MySQL allows duplicate NULL values for unique constraints. So, you can do one of two things:
Use a default value, such as '2099-12-31' for time out.
Use a trigger to enforce uniqueness
In either case, the database itself will be validating the data, so you can be confident of data integrity regardless of how the data is inserted or updated.
I did it from my mobile not tested but you will get the idea of what is going on
if(isset($check))
{
$sql="SELECT * FROM dtr WHERE userID = $userID";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo "Already in";
if(isset($check['timeIN']) && !isset($check['timeOUT']))
{
$sql = "UPDATE dtr SET timeOUT= now() WHERE userID=$userID";
mysqli_query($con, $sql);
mysqli_close($con);
}
}
else
{
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
mysqli_close($con);
echo 'Time IN Successful!';
}
}
else
{
echo 'Invalid USER ID. Please try again!';
mysqli_close($con);
}

How to insert values in database if it set foreign key?

<?php
if(isset($_GET['email']) && !empty($_GET['email']))
{
$email = mysql_real_escape_string($_GET['email']);
$sml="UPDATE USERS SET password=$_POST[password] where email='$email' ";
$account=mysql_query("INSERT INTO ACCOUNT(email) SELECT email from USERS WHERE email='$email' ") or die('Error:' .mysql_error());
if (mysql_query($sml,$con))
{
header('Location: ../home.html');
}
else{
die('Eror: ' . mysql_error());
}
}
else
{die('Eror: ' . mysql_error());}
mysql_close($con);
?>
How to insert email in account table its an foreign key for the account table.
I want to insert same email value to the account table for the other table reference.
You have to add user/s first. You can't add a record into Accounts table if you don't have a matching record in the parent(Users) table.
That is how foreign key constraint works. For example if you have a record in Users table with user_id = 1, you are only allowed to have records with user_id = 1 in the Accounts table. And so on...
Hint 1:
Try not to put $_POST['key'] directly into query because that makes it vulnerable to sql injection.
Hint 2:
Use exit after header function.

Duplicate entry '' for key 2

Here is the php code that gives me "Duplicate entry '' for key 2" error...
<?php
$host = "localhost";
$user = "admin";
$pass = "123";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$userid= mysql_real_escape_string($_POST['userid']);
$latitude= mysql_real_escape_string($_POST['latitude']);
$longitude= mysql_real_escape_string($_POST['longitude']);
//$time= mysql_real_escape_string($_POST['time']);
$db_select=mysql_select_db("new");
if(!$db_select){
die(mysql_error());
echo "error";
}
$query= "INSERT INTO location(Userid, Latitude, Longitude )
VALUES ('{$userid}', '{$latitude}', '{$longitude}'); " ;
if($medo=mysql_query($query)){
header("localhost/filename");
exit;
}else{
echo"<p> Error</p>";
die(mysql_error());
}
I don't think there is a problem with my code. please help.
As I suppose you'll want to update if already present, use this syntax for your MySQL request :
$query= "INSERT INTO location (Userid, Latitude, Longitude )
VALUES ('{$userid}', '{$latitude}', '{$longitude}')
ON DUPLICATE KEY UPDATE Latitude='{$latitude}', Longitude='{$longitude}';";
So that when your user already exist, it will be updated with the new coordinates
if the user_id is primary key make it auto increment and don,t post this value from front end.
if it is not a primary key than it will be definitely a unique key. so before insertion first check that record already exists or not.
If you want the unique record for each user, you have to check if user record already exists, then use UPDATE instead of INSERT.
If there are many records for each user, just remove PRIMARY KEY or UNIQUE KEY from 'Userid' column.

replace not updating in database

I have a table with id which is the primary key and user_id which is a foreign key but the session is based on this in my code.
I have tried EVERYTHING, so I will post my full code.
The form should insert if there is not a user_id with the same session_id in the table. If there is, it should update.
At the moment, when the user has not visited the form before (no user_id in the table) and data is inserted in, the page returns to the location page: but the data is not inserted in the table. if the user changes the data once it is updated it doesn't change either.
This is the table structure:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
`complete` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
The code I have been using (and failing):
$err = array();
$user_id = intval($_SESSION['user_id']);
// otherwise
if (isset($_POST['doThesis'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// check if current user is banned
$the_query = sprintf("SELECT COUNT(*) FROM users WHERE `banned` = '0' AND `id` = '%d'",
$user_id);
$result = mysql_query($the_query, $link);
$user_check = mysql_num_rows($result);
// user is ok
if ($user_check > 0) {
// required field name goes here...
$required_fields = array('thesis_Name','abstract');
// check for empty fields
foreach ($required_fields as $field_name) {
$value = trim($_POST[$field_name]);
if (empty($value)) {
$err[] = "ERROR - The $field_name is a required field" ;
}
} // no errors
if (empty($err)) {
$id = mysql_real_escape_string($_POST['id']);
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
//replace query
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query))
echo "the query failed";
else header ("location:myaccount.php?id=' . $user_id");
}}}
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
class="forms">
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?> </textarea>
</tr>
<tr>
<td>Abstract<span class="required">*</span>
</td>
<td><textarea name="abstract" style="width:500px; height:150px"
type="text" id="abstract" size="600"><?php echo $row_settings['abstract']; ?>
</textarea></td>
</tr>
<?php }
} else { ?>
//shows fields again without echo
I've tried var_dum($query) but nothing appears
PS I know the code isn't perfect but I'm not asking about this right now
I can't see how your replace statement will ever insert the initial row, as the where clause is always going to be false (there won't be a row with that user Id).
I think of you want to use replace you need to replace into thesis (id, userid, etc) without a where clause. If id and userid have a unique constraint and a row for userid exists then it will be updated; if it doesn't exist it will be inserted.
However- if you don't know id- which you won't if you are using auto increment, then I'm not sure you can do this with replace. See http://dev.mysql.com/doc/refman/5.0/en/replace.html
Why don't you check for the existence of a row an then use update or insert?
BTW, is the idea that a user can enter multiple theses into a form, or just one? Your table suggests they can have multiple. If this is what you are trying to achieve then I think you should be storing the id of each thesis in a hidden field as part of the form data. You would then be able to use REPLACE INTO thesis (id, user_id, thesis_name, abstract) VALUES ($id, $user_id, $thesis_name, $abstract) where id is the id of the thesis obtained from each hidden field. If this is not present, i.e. the user has entered a new thesis, then use NULL for id in the insert. This will work using the REPLACE INTO as the id column is auto increment.
Perhaps you mean user_id not id:
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE user_id='{$_SESSION['user_id']}'";
Or if you do mean the id from $_POST['id']
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE id='$id'";
Also instead of REPLACE you should use UPDATE. Im pretty sure its faster because REPLACE basically deletes the row then inserts it again, im pretty sure you need all the fields and values else your insert default values. From the manual:
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT
So you should use:
$query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE id='$id'";
You are doing everything right just one thing you are doing wrong
Your replace query variable is $query and you executing $the_query.
you wrong here:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query)) // this is wrong
echo "the query failed";
replace it with:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($query)) // use $query
echo "the query failed";

Categories