How can I insert the last Id into the child table : - php

I am trying to insert into two tables the mother table and the child table : but the mother table gets the data and the child table does not : I get the error
Cannot add or update a child row: a foreign key constraint fails (portfolio.players, CONSTRAINT players_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE)
And bellow is my code :
$query="INSERT INTO users(email,date)
VALUES('$email','$date')";
$user_result = mysql_query($query);
/*last inserted Id */
$id_last = ("SELECT LAST_INSERT_ID()");
$res = mysql_query($id_last);
$last_id = mysql_fetch_array($res);
/*last inserted Id ends*/
/*insert query */
$sql="INSERT INTO
players(name, surname, position, contact_number, email, username, password, date, user_id)
VALUES('$name ','$surname','$position','$contact_number','$email','$username','$password', '$date', '$last_id')";
$result = mysql_query($sql)or die (mysql_error());
/*if something goes wrong then tell the user*/
if($result){
echo "Player Successfully added</br>";
}
else {
echo "We are sorry no player inserted ";
}

$last_id = mysql_fetch_array($res);
mysql_fetch_array returns array, to get actual id you should use $last_id[0]. Also there is function for that: mysql_insert_id. While looking on linked manual page, please pay attention to big red frame, and continue developing with either mysqli or PDO.

Related

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

Inserting values to mysql database and retrieving them to insert to another table

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.

Referential Integrity Error

I am having a bit of trouble with referential integrity errors on my database final exam project. I have tried to figure it out myself, but to no avail, and I am hoping someone here can point me in the right direction.
The problem is that I have three tables with the first two being parent tables to the third table. I am trying to construct a php script that will update the two parent tables and then insert the data into the child table. What I have thus far, I thought would work, but whenever I try to use it, I get the following error:
INSERT INTO Purchases (CustomerID, PurchaseOrderNo, PurchaseTotal, DateOfPurchase, SalesPersonID,SpecialOrder) VALUES ('10', '0000','100.00','0000-00-00','5555','N')
Cannot add or update a child row: a foreign key constraint fails ('xxxxxx'.'Purchases', CONSTRAINT 'Purchases_ibfk_1' FOREIGN KEY ('CustomerID') REFERENCES 'CustomerInfo'('CustomerID') ON DELETE CASCADE ON UPDATE CASCADE)'
Any thoughts where I have gone wrong?
########## FOREIGN KEY CHECK START ##########
$sql = "select count(*) as count from CustomerInfo where '$customerid' = CustomerID";
$result = mysqli_query($con,$sql)
or die('Error: ' . mysql_error());
$row = mysqli_fetch_assoc($result);
if ( $row['count']==0 ){
"INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid');";
echo "<p>Customer ID Not Found. <br />New CustomerID Created.</p>";
}
$sql2 = "select count(*) as count from EmployeeInfo where '$salespersonid' = SalesPersonID;";
$result2 = mysqli_query($con,$sql)
or die('Error: ' . mysql_error());
$row2 = mysqli_fetch_assoc($result2);
if ( $row2['count']==0 ){
"INSERT INTO EmployeeInfo ('SalesPersonID')VALUES ('$salespersonid');";
echo "<p>Salesperson ID Not Found. <br />New Salesperson ID Created.</p>";
}
########## FOREIGN KEY CHECK END ##########
########## DATA ENTRY SQL STATEMENT START ##########
$sql3 = "INSERT INTO Purchases (CustomerID,
PurchaseOrderNo,
PurchaseTotal,
DateOfPurchase,
SalesPersonID,
SpecialOrder)
VALUES ('$customerid',
'$purchaseorderno',
'$purchasetotal',
'$dateofpurchase',
'$salespersonid',
'$specialorder')";
########### DATA ENTRY SQL STATEMENT END ##########
########## INPUT SUCCESS/FAILURE REPORTING#########
if (mysqli_query($con, $sql3)) {
echo "<P>Record Successfully Created</P><BR />";
} else {
echo "Error: " . $sql9. "<br>" . mysqli_error($con);
}
mysqli_close($con);
echo "<P>Connection Successfully Closed.</P>";
You aren't executing your insert queries for CustomerInfo or EmployeeInfo
$sql = "select count(*) as count from CustomerInfo where '$customerid' = CustomerID";
$result = mysqli_query($con,$sql)
or die('Error: ' . mysql_error());
$row = mysqli_fetch_assoc($result);
if ( $row['count']==0 ){
###THE NEXT LINE DOESN'T DO ANYTHING###
"INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid');";
echo "<p>Customer ID Not Found. <br />New CustomerID Created.</p>";
}
Also you don't want to put single quotes around the column name in your insert statements so instead of:
INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid')
you want:
INSERT INTO CustomerInfo (CustomerID) VALUES ('$customerid')

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

Problem with syntax error

Hi guys am fighting with a syntax error of my sql, saying exactly:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax"
Even though the code is working and doing what I wanted I still get the syntax error info!
and here is the code:
$person_id =mysql_query("SELECT person_id FROM person WHERE firstname='$array[0]' AND lastname='$array[1]' AND city='$array[2]' ")
or die(mysql_error());
if (mysql_num_rows($person_id) )
{
print 'user is already in table';
}
else
{
mysql_query ("INSERT INTO person VALUES (NULL, '$array[0]' ,'$array[1]' , '$array[2]' ")
or die(mysql_error());
$person_id = mysql_insert_id();
}
$address_id =mysql_query("SELECT address_id FROM address WHERE street='$array[3]' AND city='$array[4]' AND region='$array[5]'")
or die(mysql_error());
if (mysql_num_rows($address_id) )
{
print ' already in table';
}
else
{
mysql_query ("INSERT INTO address VALUES (NULL, '$array[3]', '$array[4]', '$array[5]'")
or die(mysql_error());
$address_id = mysql_insert_id();
}
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)")
or die(mysql_error());
Thanks for any suggestions
It's probably because you haven't escaped your values...
Try:
$query = "SELECT age FROM person WHERE name='".mysql_real_escape_string($array[0])."' AND lastname='".mysql_real_escape_string($array[1])."' AND city='".mysql_real_escape_string($array[2])."'";
And read up on SQL injection.
EDIT
I think your problem is that you are trying to pass mysql result resources directly into a string, without fetching the actual values first.
Try this:
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the person already exists in the database, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]')";
mysql_query($query) or die(mysql_error());
$person_id = mysql_insert_id();
}
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// INSERT a record linking person and address
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)") or die(mysql_error());
ANOTHER EDIT
Firstly, I have modified the code above - added a couple of comments, corrected a couple of small errors where the wrong variable was referenced and re-spaced it to make it more readable.
Secondly...
You are getting that additional error because you are trying to insert a new row into your person_address table, which doesn't seem to have a sensibly configured primary key. The easy work around to the problem you currently have is to run a SELECT against this table to see if you have already got a record for that user, then if you have you can do an UPDATE instead of the INSERT to alter the existing record.
However, if I understand what your doing here correctly, you don't actually need the person_address table, you just need to add another integer column to the person table to hold the ID of the corresponding row in the address table. Doing this would make many of your future queries potentially much simpler and more efficient as it will be much easier to SELECT data from both tables at once (you could do it with your current structure but it would be much more confusing and inefficient).
The following code example could be used if you add another integer column on the end of your person, and call that column address_id. You will notice it's very similar to the above, but there are two key differences:
We do the address stuff first, since we will keep track of the relation in the person record
We do an UPDATE only if we find a person, otherwise we just INSERT a new person as before
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// See if the person already exists in the database, UPDATE if he does, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
$query = "UPDATE person SET address_id = '$address_id' WHERE person_id = '$person_id'";
mysql_query($query) or die(mysql_error());
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]', '$address_id')";
mysql_query($query) or die(mysql_error());
}
If we structure the database in this way, it allows us to do this:
SELECT person.*, address.* FROM person, address WHERE person.address_id = address.address_id AND [some other set of conditions]
Which will return the person record, and the address record, in the same result set, all nicely matched up for you by the database.
YET ANOTHER EDIT
You need to add an auto-increment primary key to the person_address table, and perform a SELECT on it to make sure you are not adding duplicate records.
You should replace the final INSERT statement with the following code segment. This code assumes that you have a primary key in the person_address table called relation_id. It also assumes that the id field names in this table are named in the same way as they are in the other two tables.
// See if a relation record already exists for this user
// If it does, UPDATE it if the address is different
// If it doesn't, INSERT an new relation record
$query = "SELECT relation_id, address_id FROM person_address WHERE person_id = '$person_id' LIMIT 1";
$relation = mysql_query($query);
if ( mysql_num_rows($relation) ) {
$relation = mysql_fetch_assoc($relation);
if ($relation['address_id'] == $address_id) {
print 'The record is identical to an existing record and was not changed';
} else {
$relation_id = $relation['relation_id'];
$query = "UPDATE person_address SET address_id = '$address_id' WHERE relation_id = '$relation_id'";
mysql_query($query) or die(mysql_error());
}
} else {
$query = "INSERT INTO person_address VALUES(NULL, '$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
EVEN MORE EDITING
Try this to replace the code from above:
// See if a relation record already exists for this user
// If it doesn't, INSERT an new relation record
$query = "SELECT person_id FROM person_address WHERE person_id = '$person_id' AND address_id = '$address_id' LIMIT 1";
$relation = mysql_query($query);
if ( !mysql_num_rows($relation) ) {
$query = "INSERT INTO person_address VALUES('$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
You cannot use array values like that inside of quotes - instead you could, for example, separate the values from the query using dots.
$query = "SELECT age FROM person WHERE name='".$array[0]."' AND lastname='".$array[1]."' AND city='".$array[2]."'";
the second and fourth query do not have an ending ')' at the end of the values

Categories