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

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

Related

How to insert primary key second table

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

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

Duplicate Data for Primary Key

I have a table that saves an ID for the user. The data for that id is gotten from LDAP
The first time the user logs in, it inserts his ID on the table. but i need to do this considering users that have data already on the database.
I get the error
Duplicate entry 'whateverdata' for key 'PRIMARY'.
Since the field it is inserting data is Primary key. But i need to get around this.
$check = "select * from utilizadores where id = '$samaccountname[0]'";
$h = mysql_query($check);
if (!$h) {
die (mysql_error());
}
$data = mysql_fetch_array($h);
if ($data[0] > 1) {
header('location:pprincipal.php');
}
else {
$query = mysql_query("insert into utilizadores (id) values('$samaccountname[0]');");
if (!$query){
die (mysql_error());
}
}
I don't want to duplicate data, i just want to check if the data is inserted, and if it is, proceed, if it isn't, insert data.
NOTE: the $samaccountname is a variable that contains data gotten from the LDAP
basicaly - The user logs in the first time and it inserts data on the database.
The second time - Since the field is Primary Key, It will fail.
In order to proceed to the main page (pprincipal.php) the user must have his data inserted on the database.
Thanks in advance.
use mysql_num_rows function in if condition.
if (mysql_num_rows($h)){
header('location:pprincipal.php');
} else {
$query = mysql_query("insert into utilizadores (id) values('$samaccountname[0]');");
if (!$query){
die (mysql_error());
}
}
You can just insert ignore data without checking if it's exist or not.
replace you code with:
$query = mysql_query("insert ignore into utilizadores (id) values('$samaccountname[0]');");
if (!$query){
die (mysql_error());
}

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.

php - duplicate entry

what should do if the entry are doubled?
<?php
require_once('auth.php');
session_start();
$exam = $_SESSION['exam'];
$subject_id = $_SESSION['exam'];
$_SESSION['sub'] = $subject_id;
$subject_title = $_POST['subject_title'];
$subject_description = $_POST['subject_description'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_compre', $con);
$sql = "INSERT INTO examsubjectrecord_table(subject_id , subject_title ,
subject_description)
VALUES ('$subject_id','$subject_title', '$subject_description')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
header("location: addsubject.php?exam=".$exam ."");
}
?>`
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\compre\admin\addsubjectacc.php on line 4
**Error: Duplicate entry '1' for key 'PRIMARY'**
It depends on yout application business-logic.
You can notify a user about a duplicated entry or silently update information with INSERT ... ON DUPLICATE KEY UPDATE ... SQL statement.
In your database you have a primary key of subject_id which cant have duplicates.
If you need to have duplicates in the subject_id column then you should add a column and set it as a primary key in your database. For example add another column unique_id and set it to auto_increment and as a primary key for row identification.
Basically, you'll first want to check if the value you're trying to insert into your primary key field already exists.
So if you primary key field is subject_id, you'd need to check if that already exists by doing a select query followed by PHP's mysql_num_rows function. For example:
$subject_id = 1337;
$check = mysql_query("SELECT `subject_id` FROM `examsubjectrecord_table` WHERE `subject_id`=" . $subject_id);
// See if anything was returned
if(mysql_num_rows($check) > 0) {
// We have something with this subject_id already!
echo "Cannot insert duplicate subject!";
} else {
// All clear, run your INSERT query here
}
Which column is your primary key? I'm going to assume that's subject_id. This needs to be unique for each row in your table. The easiest way to ensure this is to use AUTO_INCREMENT and then avoid inserting the subject_id at all. It will be assigned automatically.
If you need to find out what the ID of new subjects is, you can use mysql_insert_id.

Categories