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')
Related
I have a table with input of type time and I want to check first if there is a row with the current date and the id of employee, if it was I update the value of the input if not I insert a new row. This is what I have tried but it always inserts a new row even if the condition exists:
<?php
$E1=$_POST['E1'];
$connect = mysqli_connect("localhost", "root", "ntr-ktb123", "absence");
$sql1="SELECT * FROM retards WHERE Date ='Curdate()' AND
IdEmpl='".$_POST["IdEmp"]."' ;";
$result1=mysqli_query($connect,$sql1);
if(!$result1){
die('ERREUR SQL ! <br>'.$sql.'<br>'.mysqli_error());}
if($dt=mysqli_fetch_array($result1,MYSQLI_ASSOC)){
$sql="update retards set E1='$E1' where IdEmpl='".$_POST["IdEmp"]."' AND
Date=CURDATE();";
}
else{
$sql="insert into retards(IdEmpl,Date,E1) values
('".$_POST["IdEmp"]."',CURDATE(),'$E1'); ";
}
$result = mysqli_query($connect, $sql);
if (!$result)
{
echo("Error description: " . mysqli_error($connect));
}
else {
$message ="Effectué avec succès!";
echo "<script type='text/javascript'>alert('$message'); </script>";
}
mysqli_close($connect);
?>
This is known as an upsert which can be done in mysql using the insert ... on duplicate key update syntax.
insert into t (a, b, c) values (?, ?, ?)
on duplicate key update b = ?
Your table should have an appropriate unique index or primary key defined on the column(s) of interest.
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);
}
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.
Im i have a php form to enter data into a mysql database, my question is how do i handle duplicate records for example if an ID number already exsists how do i check if exsists then if it does throw an error message, for expale saying "ID is already in the database",here is an example of an insert statement, however i would like it to check the database for duplicate records before entering
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
As long as there is a suitable UNIQUE KEY or PRIMARY KEY on the field that needs to be unique you will receive an error when you try to insert the duplicate record. You can then test for this error in your code.
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id) VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
if (mysql_errno() == 1586) {
echo "ID is already in the database";
} else {
die('Invalid query: ' . mysql_error());
}
}
do a select like : select count(loan_id) from load where load_id=$values[loan_id]
than if result>0 don't insert and give error message "ID is already in the database" to user, otherwise insert it.
eigther check before inserting or do and update.
check
"SELECT COUNT(*) FROM loan WHERE loan_id = '" . $values['load_id'] . "'"
update
"INSERT INTO loan (loan_id, some_field) VALUES ('". $values['loan_id'] ."', '". $values['some_field'] ."') ON DUPLICATE KEY UPDATE some_field = VALUES(some_field)";
Add a unique index constraint on the loan_id column. MySQL will throw an error when your application attempts to insert another row with the same value.
SQL will look similar to:
CREATE UNIQUE INDEX loan_id_index ON table_name (loan_id);
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