I am using ON DUPLICATE UPDATE on my query, some of the result didn't store it. I tried all the possible way, but those still remain the same. here are the database picture.
Those NULL, is the row which didn't store successfully; the result should be 1 instead of NULL.
if($remark){
$query3 = "INSERT INTO `audit_section_remarkrecord` SET remark = '$remark', form_details_subquestion_id = '$form_details_subquestion_id', form_details_section_id = '$form_details_section_id', audit_section_no = '$audit_no' ON DUPLICATE KEY UPDATE
form_details_section_id = '$form_details_section_id' , remark = '$remark'";
$result3 = $db->query($query3);
$query4 = "UPDATE `remarkrecord_update_details` SET form_details_section_id = '$form_details_section_id', userlog = '$user_staff', ipaddress = '$ip' WHERE form_details_subquestion_id = '$form_details_subquestion_id' AND audit_section_no = '$audit_no' ";
$result4 = $db->query($query4);
}else{
}
}
Table Structure
Try changing one of your columns you are inserting value to primary key or add UNIQUE constraint to the column.
ALTER TABLE audit_section_remarkrecord ADD UNIQUE KEY (your column);
As there is currently only a unique key on the Primary Key, an auto-increment, you are going to have difficulty generating a unique key clash on an insert on duplicate key update (IODKU). Therefore, some other unique key needs to be created (even a composite), that will trigger the clash of a unique key and allow IODKU to work as expected.
Related
I was trying to find out what was wrong with my code.
This is the error I'm recieving
"Cannot add or update a child row: a foreign key constraint fails "
This is my code
<?php
$sql = "INSERT INTO stasjon (navn) VALUES ('skogen', 'voksenlia') ";
$resultat = $kobling->query ($sql);
$sql ="SELECT * FROM stasjon WHERE navn = ('skogen')";
$resultat = $kobling->query ($sql);
while ($rad = $resultat->fetch_assoc()) {
$stasjon_id = $rad['stasjon_id'];
}
$sql = "INSERT INTO linjestasjon (linje_nr, stasjon_id) VALUES ('1','$stasjon_id')";
$resultat = $kobling->query ($sql);
if($kobling->query($sql)) {
echo "Spoerringen $sql ble gjennomfoert.";
} else {
echo "Noe gikk galt med spoerringen $sql ($kobling->error).";
?>
Some of it is in Norwegian because That's the language of the database I'm making. I was trying to add values to two different tables (that had stasjon_id as a foreign key) Thanks in advance
Foreign Key constraints checks in the value that you are inserting or updating to a particular filed exists in some other filed of another table. Suppose I have 2 tables as follows
CREATE TABLE TableA
(
SeqNo INT PRIMARY KEY,
Name VARCHAR(500
)
CREATE TABLE TableB
(
SeqNo INT NULL FOREIGN KEY REFERENCES TableA(SeqNo),
Name VARCHAR(50)
)
So when you insert a new record to the Tableb.SeqNo filed, The value should either be NULL or some value that exists in the TableA.SeqNo.
So Before inserting the values make sure that you are inserting the value that satisfy your foreign key constraint
Is there a better or faster way to return the ID?
The column customer is unique
$inserted_id = null;
if( !$mysqli->query("INSERT INTO users (id,customer) VALUES(null,'foo')" ){
// Is it possible to avoid this 2nd query?
$result = $mysqli->query("SELECT id FROM users WHERE customer='foo'");
$inserted_id = $result->fetch_assoc()['id'];
} else {
$inserted_id = $mysqli->insert_id;
}
Use $last_id = $mysqli->insert_id(); after your insert. That get's the last generated auto increment. Your code as it stands will not be accurate. Updated for Object Oriented perspective.
You can modify the insert query to UPDATE auto incremented column when a duplicate record is attempted to INSERT.
INSERT INTO users (id,customer)
VALUES (null,'foo')
ON DUPLICATE KEY UPDATE
id = LAST_INSERT_ID(id)
id = LAST_INSERT_ID(id) will return the value of the AUTOINCREMENT column for the last INSERT and set the value for mysqli_insert_id. This will make last insert id available during all inserts.
Have modified your code:
$inserted_id = null;
if($mysqli->query("INSERT INTO users (id,customer) VALUES(null,'foo') ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)" )
{
$inserted_id = $mysqli->insert_id; // Will return last insert ID in case of successful inserts as well as failed inserts due to duplicate key
}
After looking around on stackoverflow, I'm still having a little trouble understanding the one-to-many relationship in mysql. I have a request coming in from the user (form submission) which will be stored in one table. This is a dynamic form that lets the user add extra fields therefore those will be stored in a separate table. So in short, in my db design, there will be one table for the users with PRIMARY KEY AUTO INCREMENT and there will be another table for the hostnames PER user (multiple fields -array) and using a foreign key that references to the primary key in the user table. Sorry if this is long but trying to make this a good question.
Example:
User Table: (ONE)
1. John Doe, blah, 11-12-15
2. Sally Po, blah, 11-14-15
3. John Doe, blah, 11-15-15
(these are three separate requests)
(numbers are primary key auto incr.)
Host Name Table: (MANY)
1. www.johndoe.com
1. www.johndoe2.com
1. www.johndoe3.com
2. www.sallypo.com
2. www.sallypo2.com
(these numbers (foreign key) should match the primary key for each request)
Code (Leaving out the actual queries + pretty sure I shouln't be using last_id):
$sql = "CREATE TABLE IF NOT EXISTS userTable (
id int AUTO_INCREMENT,
firstName VARCHAR(30) NOT NULL,
date DATE NOT NULL,
PRIMARY KEY (id)
)";
//query
$sql = "CREATE TABLE IF NOT EXISTS hostNamesTable (
id int NOT NULL,
hostName VARCHAR(90) NOT NULL,
FOREIGN KEY (id) REFERENCES userTable(id)
)";
//query
$sql = "INSERT INTO userTable (firstName, date)
VALUES ('$firstName', '$date')";
//query
$last_id = mysqli_insert_id();
for($i = 0; $i < sizeof($hostName); $i++){
$sql = "INSERT INTO hostNamesTable (id, hostName)
VALUES ('$last_id', '$hostName[$i]')";
//query
}
What am I doing wrong? (is this the right way to go about it?)
note: I was trying to get the last_id of the user Table so that I can use it in the hostName table as the foreign key
EDIT: I'm using MySQLi with php
EDIT 2:
After the changes, this is the error I am getting now: Cannot add or update a child row: a foreign key constraint fails (d9832482827984hb28397429.hostNamesTable, CONSTRAINT hostNamesTable_ibfk_1 FOREIGN KEY (id) REFERENCES userTable (id))Error: INSERT INTO hostNamesTable (id, hostName, ) VALUES ('', 'secondhost.net')
--Looks like the $last_id isn't even being recorded?
EDIT 3: Started working. Not sure what it was but I think it was because of some type.
why dont you just add an extra column in the hostNames table which is called "ref_user" and contains the ID of the user you are reffering to? So you can use unique IDs in both tables.
Make a query like:
SELECT * FROM hostNames WHERE ref_user = (SELECT id FROM userTable WHERE <uniqueColumn> = <uniqueIdentifierOfUser>);
But the included request must return only one line from users.
try adding mysqli $link as a parameter in your mysqli_insert_id
$last_id = mysqli_insert_id($link);
i presume you have this somewhere in your code
$link = mysqli_connect("localhost", "mysql_user", "mysql_password", "mysql_db");
if this doesn't work, try using mysql LAST_INSERT_ID() function
$last_id = $mysqli->query("SELECT LAST_INSERT_ID() AS last_id")->fetch_object()->last_id;
I have a DB with a unique number and a badge number. the badge number will change but the unique number wont.
|unique_number|badge_number|
|-------------|------------|
|1234 |2 |
|-------------|------------|
I want to be able to update badge_number in relation to unique_number without creating a new row (un-checking the key "unique"). But currently I get the error Error: Duplicate entry '1234' for key 'unique_number'
if I post this code:
$sql="INSERT INTO table (unique_number, badge_number) VALUES ('1234', 1)";
I have tried this:
$sql="INSERT INTO push (unique_number) VALUES ('".$_POST['unique_number']."')";
$sql2="UPDATE table set badge_number= 0 where unique_number=".$_POST['unique_number']."";
if (!mysqli_query($con,$sql))
{
echo'Error: ' . mysqli_error($con);
}
if (!mysqli_query($con,$sql2))
{
die('Error2: ' . mysqli_error($con));
}
If you make a primary key or a unique constraint applied to a column, any insertion of new data must verify the uniqueness of data based on that column. So I guess you have a constraint applied to the unique_numberColumn.
But you still change Data of an exesting row if and only if you the new data verify existing data.
UPDATE table SET badge_number = 1 WHERE unique_number = '1234'
INSERT queries are responsible to insert new records in table.
Hence if you are trying to insert a new row with unique_number=1234, it is violating unique key constraint and generates error Error: Duplicate entry '1234' for key 'unique_number' as there is already a record with this unique_number=1234.
If you want to update the existing record, you can use update query to update any record.
So if you need to update record where unique_number=1234, you need to use following query:
UPDATE table_name SET badge_number = 3 WHERE unique_number = 1234
Something like the following?
$sql = "UPDATE table SET badge_number = '0' WHERE unique_number = '$_POST['unique_number']'";
There is my code:
$sql = "INSERT INTO item SET
player = '$player',
amount = '$amount',
item = '$item',
allowed = '$allowed' ON DUPLICATE KEY UPDATE
amount = amount + $amount";
When I executing this query, in database creates new row despite the fact that it already exists...
Thanks for help.
In the comments, you say there are no keys on the table. That's a problem. You're asking the database ON DUPLICATE KEY UPDATE, but without a UNIQUE KEY, it has no idea what a DUPLICATE KEY is.
You need to add a UNIQUE KEY (or a PRIMARY KEY) on the field(s) you don't want being duplicated.
The syntax is not correct, this corrected version:
$sql = "INSERT INTO item SET
player = '$player',
amount = '$amount',
item = '$item',
allowed = '$allowed'
ON DUPLICATE KEY UPDATE
amount = `amount` + '$amount' ";
Other factor depends on your table structure and the key
I would do it like that:
$sql = "INSERT INTO DBNAME.item (player, amount, item, allowed)
values('$player', '$amount', '$item', '$allowed')
ON DUPLICATE KEY UPDATE
amount = amount + values(amount);";