"insert on duplicate update" still inserts duplicates - php

I have a mysql table with descriptionId as a primary key and it is auto incremented. it also has a "content" and a "price" columns and few more.
I also have a form consisting of multiple input boxes with the current database values of my price and content columns in my description table. after submitting the form i'd like to update the table with the new values and if any of the input boxes is deleted, the record must be deleted from the table.
I have also managed to define three arrays to hold the values of all my tables' columns. These Arrays are as followed: $descrId,$content,$price
when i submit my form, the php file loops through theses arrays and executes the following query:(I have validate these arrays so they work just fine)
INSERT INTO
description(descriptionId,content,price,orderNo,salesPerson,dateTime,updated)
VALUES('{$descrId[$k]}','{$content[$k]}','{$price[$k]}','{$orderId}','{$sale}',NOW(),1 )
ON DUPLICATE KEY UPDATE content=VALUES(content),price=VALUES(price),updated=1, dateTime=NOW()
However, this query keeps duplicating the values anytime i press submit.
I appreciate your time....

As I read your question ON DUPLICATE KEY will never occur, because your primary key is an auto incremented value, which will be +1 each time your insert something in the table, so it will never have a duplicated value - that's the idea more or less behind AUTO INCREMENT.
So the answer is to pick another column, i.e. orderNo or dateTime, make it UNIQUE and then try again with the query.
Update
Alternatively you can combine two or more columns and define them as a (unique) key.
If that's also not applicable in your case, then use some hashing function/algorithm when inserting the data and store that hash along the other values in the table.

Related

How to write Insert and Update query in one single Query in mysql

I have below mentioned Issue.
I am developing inventory system using php.
According to that i have to add invoiced items to table.
Dynamically generated text box used to collect received item details.
I have current_stock table and it contain Item-name and qty columns.
Item-name is primary key field.
item which i am going to insert if already exist quantity should be updated with new value.
if it is not exist should be inserted as a new row.
This is must be done in loop because i use dynamically genarated text box and data collect using $item[] and $qty[] arrays.
I am try to use several ways to solve this issue unable to execute in for loop but not yet success.
please help me.........
you can try this :
INSERT INTO table (id, item_name, qty) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
item_name="A"
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.
for multiple query excution you have to use
mysqli_multi_query()
like this :
mysqli_multi_query("INSERT INTO TABLE SET Field='Value',FieldB='ValueB';
UPDATE TABLE SET Field='Value',FieldB='ValueB' WHERE FIELDID='VALUEID';")
i hope this will work.have fun.

Insert multipe rows for the same value - SQL

How can I insert more than one row for the same value
for example, each user has to submit 2 forms so the username is the same in each form but the information is different
I tried to use UPDATE but it removes the ole information and replaces it with the new one while I want to keep both
is there a way to do that?
insert into your_table (username, col2)
values ('user1', 1),
('user1', 2)
Have two tables, 'USERS' and 'FORMSUBMISSIONS'
When a user submits a form for the first time, a new entry is created in the USERS table, which is unique for each user, and would contain information connected to the user.
And whenever a form is submitted (including the first time), an entry is written to the FORMSUBMISSIONS table with the details of that submission, and a foreign key back to USERS.
That's a cleaner data model for this situation. It will also help future queries on the data. If you are limited to a single table for some reason, then successive inserts will work as above, as long as there is no unique key on the USER field.
you can add duplicate data just your primary key can't be duplicated because it causes primary key constraint. so what you can do is have an extra column let's say "ID" make it your primary key. While submitting the row keep on adding ID column's value by one, rest of the data could be same.
It depends on whether your USERNAME column allows duplicates.
If it's the primary key of the table, your table schema doesn't support what you want to do, because PK should be UNIQUE.
If your USERNAME column allows duplicates, you can use INSERT:
declare #username varchar(max) = 'your_username' --declare a variable to use the same username
insert into table_name (username, form_data)
values(#username, 'form_data_1')
,(#username, 'form_data_2')
It also depends on how you're executing the SQL statement. I would definately go and create stored procedure to do this insert.
you can use bulk insert query for that. as suggested by #huergen but make sure that your username or any field that might be in form data does not have UNIQUE key index. you can also add another field that works like PRIMARY key in that table.so many ways to do but it depends upon your requirement.
Use below insert format to get your desired result:
insert into Table_name(Field1, Field2)
SELECT 'user_1', 1 UNION ALL
SELECT 'user_1', 2

Adding to a database field instead of overwriting it (MySQL UPDATE function)

I am trying to update an emails field in my database... when one of our teachers sends an invitation through our system the invited email is recorded in our database.
I want the teacher to be able to send the email, and then if they forgot someone they can send another invite and the database field will then hold for example two emails (the original and then the added one).
Here is the code that I have to store the emails in the DB...
$recipientemail = $_POST['recipientemail'];
// Stores the (instance) in the instance database
include_once("$_SERVER[DOCUMENT_ROOT]/classes/includes/dbconnect.php");
$sql = ("UPDATE `database1`.`instances` SET `invitemail` = '{$recipientemail}' WHERE `instances`.`instance` = '{$instance}';");
$query = mysqli_query($dbConnect, $sql)or die(mysql_error());
This code overwrites the originally invited email whenever I invite a new person... many thanks for your consideration!
Update
The solution was in the form of the MySQL "concat()" function. I should have probably been clearer that I am not working with numerical values but rather strings (email addresses). So if we look at the example in the answer below:
UPDATE table SET c=c+1 WHERE a=1;
Here it's adding c and one mathematically, I wanted to add the emails to my database even separated by a comma so I simply did this...
UPDATE table SET c = concat(c, ',', 'new#email.com') WHERE a=1;
Works like a CHARM! ;-) And thanks for all the answers!
Try to use INSERT ... ON DUPLICATE KEY UPDATE
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row.
For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;
(The effects are not identical for an table where a is an auto-increment column. With an auto-increment column, an INSERT statement increases the auto-increment value but UPDATE does not.)
The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, and 2 if an existing row is updated.
Hope this will help.

Auto Increment a row (ID)

I'm trying to AUTO_INCREMENT a row.
When creating a row for the table, is INT better than TEXT? I use varchar for the other rows, but I presume using AUTO_INCREMENT with varchar would be completely pointless.
The row is called 'ID', and is suppose to AUTO_INCREMENT every time data is inserted into other rows. Since its suppose to AUTO_INCREMENT, rather than the other rows which allows the user to input data, would it be better to modify 'serverid' below, or disable input on the ID field of my HTML form?
Here is my code:
// Inserting input values into its respected row
$serverip=$_POST['post_serverid'];
$serverid=$_POST['post_serverip'];
$serverid=$_POST['post_serverport'];
$serverid=$_POST['post_servertitle'];
$serverid=$_POST['post_serverdesc'];
$serverid=$_POST['post_serverwebsite'];
$query = mysqli_query($con,"INSERT INTO servers (serverid, serverip, serverport,
servertitle, serverdesc, serverwebsite) VALUES
('$serverid','$serverip','$serverport','$servertitle','$serverdesc','$serverwebsite')");
When defined for an AUTO INCREMENT, there is no meaning in inputting values manually.
And at times there is also a chance that you unknowingly input a value that already present in the table. To avoid such possibilities, you better omit the auto incremented field from the insert statement.
And if you still are interested to use the field in the insert statement, you can safely use a NULL or a 0(zero) into it. So that the engine will replace it with the new value from the auto increment and use it for insertion.
If you are inputting the values from a web form, you can remove the auto increment field from the form.
You shouldn't have to increment the ID from your html/php anywhere. You should set that in the database itself, as an INT with a PRIMARY index and AUTO_INCREMENT checked. Then every entry will be assigned a unique id which you can query later.

How to check insert values are different given same primary key?

If I have an insert statement with a bunch of values where the first value is an id that's also the primary key to my database, how can I check if everything else in those values is not completely the same and to update the fields that are different? (second part not necessary for an answer, but it'd be nice. If it's too convoluted to do the second part I can just delete the record first and then insert the full line of updated values)
I'm guessing that it has something to do with SELECT FROM TABLE1 * WHERE id=1 and then somehow do an inequality statement with the INSERT INTO TABLE1 VALUES ('1','A'... etc.) but I'm not sure how to write that.
Edit: I think I asked the question wrong so I'll try again:
I have a database that has first column id that is a primary key and then a lot of other columns, too long to type out by hand. I have a script that will get data and I will not know if this data is a duplicate or not e.g.
id value
1 dog
2 cat
if the new info coming in is "1, dog" then I need a signal (say boolean) that tells me true, if the new info is "1, monkey" then I need a signal that tells me false on the match and then update every single field. The question is how do I generate the boolean value that tells me whether the new values with the same id is completely identical to the one in the db? (It has to check every single filed of long list of fields that will take forever to type out, any type of output would be good as long as I can tell one means it's different and one means it's the same)
A side question is how do I update the row after that since I don't want to type out every single field, my temporary solution is to delete the row with the out of date primary id and then insert the new data in but if there is a fast way to update all columns in a row that'd be great.
MySQL can do "on duplicate key update" as part of the insert statement:
INSERT INTO table (id, ...) VALUES ($id, ...)
ON DUPLICATE KEY UPDATE somefield=VALUES(somefield), ...=VALUES(...)
Simple and effective. You only specify the fields you want changed if there is a primary key duplication, and any other fields in the previously-existing record are left alone.

Categories