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);
}
Related
Here is My Code. Its all working fine. But Some Times it inserting Duplicate Data. Why? I mean i placed the code so that same quize_no and phone combination should not submitted. But Some time its Inserting the Same quize_no and phone combination. Why is this Happening?
$sql = mysqli_query($con,"SELECT * FROM user_mm WHERE phone='$phone'");
while($row = mysqli_fetch_array($sql)) {
$name = $row['name'];
}
date_default_timezone_set("Asia/Dhaka");
$date = date('Y-m-d');
$time = date('h:i:s a', time());
$result = mysqli_query($con,"SELECT id FROM score_mm WHERE phone='$phone' AND quize_no='$quize_no' ");
$count=mysqli_num_rows($result);
if($count>0)
{
echo "1";
}
else
{
// Here I am Inserting Value in to Database
$query = mysqli_query($con,"insert into score_mm(name, phone, quize_no, score, date, time) values ('$name', '$phone','$quize_no', '$score', '$date', '$time')");
echo "Score Submitted Succesfully";
mysqli_close($con);
}
If there should truly never be a situation where you end up with duplicate quize_no and phone combinations in that table, then the first thing you should do is change your table structure to add a unique key to those columns.
For example:
ALTER TABLE score_mm ADD UNIQUE (quize_no, phone);
This won't fix whatever is causing multiple insert requests to be called, but it would at least protect your data integrity by not allowing any rows with duplicate value combinations.
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();
I'm trying to insert values to mysql database table called pointofcontact and then retrieve the primary key called pocid to insert to another table called students.
Somehow my code always return the pocid to be 0 and i have no idea why. Gladly to get some help. Any help would be greatly appreciated! Here is my code:
$query="insert into pointofcontact(Username,Password,FirstName,LastName,ContactNumber,EmailAddress,Address,Gender,Status,BackupContactNumber,ProfilePic) values ('$username','$password','$firstname','$lastname','$mobilenumber','$email','$address','$gender','Normal','$backup','$attch')";
if($con->query($query) === TRUE)
{
$query2="select POCID from pointofcontact where username= '$username'";
$result2=$con->query($query2);
if($result2 ->num_rows > 0)
{
while($row2 = $result2->fetch_assoc())
{
$pocid = $row2['POCID'];
$query3= "insert into student(StudentFirstName, StudentLastName, Allergies, NRIC, POCID) values ('$cfirstname','$clastname','$callergies','$cnric','$POCID')";
}
if($con->query($query3) === TRUE)
{
}
else
{
}
}
}
else
{
echo "error";
}
I haven't tested this, but it should do what you need:
// assuming proper validation and escaping is completed...
if($con->query("INSERT INTO pointofcontact (Username,Password,FirstName,LastName,ContactNumber,EmailAddress,Address,Gender,Status,BackupContactNumber,ProfilePic) VALUES ('$username','$password','$firstname','$lastname','$mobilenumber','$email','$address','$gender','Normal','$backup','$attch');"){
$POCID=$con->insert_id;
if($con->query("INSERT INTO student (StudentFirstName, StudentLastName, Allergies, NRIC, POCID) VALUES ('$cfirstname','$clastname','$callergies','$cnric','$POCID');")){
// Pass
}else{
// Fail
}
}else{
// Fail
}
check your database table design for POCID column. When you created that table you must add it as primary key and auto_increment ...
CREATE TABLE table_name (id int primary key auto_increment,....)
If you already did this then, use mysqli_insert_id() to get the last inserted id.
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());
}
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.