Update record only if another column matches? - php

I'm trying to develop a simple tracking system. What I'm trying to do is either insert the new record or update the record IF it matches the same campaign. I want to insert a new record if the user is triggered on a new campaign. Here is my current query that work fine.
INSERT INTO `tracking` (`email`,`ip`,`referrer`,`campaign`,`timestamp`)
VALUES ('$campaign[0]','$ip','$referrer','$campaign[1]','$timestamp')
ON DUPLICATE KEY UPDATE `last_timestamp` = '$timestamp'
My goal is if joe#bob.net triggers campaign1, then it will INSERT the record. If he tries campaign 1 again, it just updates the timestamp. Now when joe#bob.net triggers campaign2, it inserts an entirely new record.
So basically I'm trying to get it to INSERT only when the user triggers a new campaign. Otherwise, I want it to update the timestamp.
Any ideas or advice I'd really appreciate it!

Unless I'm missing something, all you need is a unique key put on the 'email' and 'campaign' columns on your table:
ALTER TABLE tracking ADD UNIQUE KEY uk_email_campaign (email, campaign);

Just add a unique key on (email, campaign) -
ALTER TABLE `tracking`
ADD UNIQUE INDEX `UQ_email_campaign` (`email`, `campaign`);

Related

MySql Update if exists insert if not

I'm trying to insert new to the table or to update the previous one in the same query.I can solve it with a bit of php code but my goal is to make it all in sql.
The problem
My app has names in different languages, I can add new languages to it.When i add new languages the translations for my products raise.
My goal is to send the script information ,and if two columns are same than the data should be updated, but if they are not they should be updated.
Here is some of my query:
"INSERT INTO product_name(link,product_id,language)
VALUES(:link,:product_id,:language) ON DUPLICATE KEY UPDATE
link=:link,product_id=:product_id,language=:language"
This query above solves one portion of the problem, but when i want to change the link it adds new data.My goal is to change the link ,and if the product_id and language are same in that row than it should be updated,if not than a new one shall be added.Unique wont solve the problem since i need to use same languages and id's in the table.
I think you just need a unique constraint on (product_id, language) -- and no unique constraint or primary key on all three columns.
CREATE UNIQUE INDEX unq_productname_product_language ON product_name(product_id, language);
This requires that the pair of values be unique, not each one individually.
Then this should do what you want:
INSERT INTO product_name(link, product_id, language)
VALUES (:link, :product_id, :language)
ON DUPLICATE KEY UPDATE link = VALUES(link);
Notice that this version uses VALUES(link). This uses the value being inserted in the statement. I think that is clearer than repeating the expression.

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.

MySQL Update if value exists, Insert if not in PHP?

$sql_career = "REPLACE INTO career
(id, battletag, lastHeroPlayed, lastUpdated, monsters, elites, hardcoreMonsters, barbarian, crusader, demonhunter, monk, witchdoctor, wizard, paragonLevel, paragonLevelHardcore)
VALUES
('', '$battletag', '$lastHeroPlayed', '$lastUpdated', '$monsters', '$elites', '$hardcoreMonsters', '$barbarian', '$crusader', '$demonhunter', '$monk', '$witchdoctor', '$wizard', '$paragonLevel', '$paragonLevelHardcore')";
ID auto increments.
battletag is unique.
Everything else changes over time. So I want to replace or update an entry if the battletag already exists without it making a new id. If it doesnt exist I want it to make a new entry letting the id auto increment for that unique battletag.
This works with one problem:
$sql_career = "
insert INTO career
(id, battletag, lastHeroPlayed)
VALUES
(NULL, '$battletag', $lastHeroPlayed)
on duplicate key
update lastHeroPlayed=$lastHeroPlayed;
";
If I, for instance, load in two unique rows, the ID auto increments to 1 and then 2 for each. Then if I load up a row that has a duplicate of the unique key of one of the existing rows (and it then updates as it should) this actually triggers the auto increment. So if I then add in a third unique row, its number will be 4 instead of 3.
How can I fix this?
You want to use the on duplicate key ... update syntax instead of replace into.
Define a unique column (primary or unique index) then check it in your statement like this:
INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
The benefit of using this over a replace into is that replace into will always delete the data you have already and replace it (sort of as the command name implies) with the data that you are supplying the second time round. An update on... statement however will only update the columns you define in the second part of it - if the duplicate is found - so you can keep information in the columns you want to keep it in.
Basically your command will look something like this (Abbreviated for important columns only)
$sql_career = "
insert INTO career
(id, battletag, heroesKilled)
VALUES
($id, '$battletag', $heroesKilled)
on duplicate key
update heroesKilled=heroesKilled+1;
";
Again, remember that in your table, you will need to enforce a unique column on battletag - either a primary key or unique index. You can do this once via code or via something like phpMyAdmin if you have that installed.
Edit: Okay, I potentially found a little gem (it's about a third of the way down the page) that might do the trick - never used it myself though, but can you try the following for me?
$sql_career = "
insert ignore INTO career
(id, battletag, heroesKilled)
VALUES
(null, '$battletag', $heroesKilled)
on duplicate key
update heroesKilled=heroesKilled+1;
";
There seems to be collaborating evidence supporting this in this page of the docs as well:
If you use INSERT IGNORE and the row is ignored, the AUTO_INCREMENT counter is not incremented and LAST_INSERT_ID() returns 0, which reflects that no row was inserted.

Is it possible to insert a row but only if a value does not already exist?

Is it possible to insert a row, but only if one of the values already in the table does not exist?
I'm creating a Tell A Friend with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.
I'm using PHP 4 and MySql 4.1.
This works if you have a unique index or primary key on the column (EmailAddr in this example):
INSERT IGNORE INTO Table (EmailAddr) VALUES ('test#test.com')
Using this if a record with that email already exists (duplicate key violation) instead of an error, the statement just fails and nothing is inserted.
See the MySql docs for more information.
If the column is a primary key or a unique index:
INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE
email=email_address
Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of "ON DUPLICATE KEY DO NOTHING" in MySQL. I'm not sure about the email=email_Address bit, you could play about and see if it works without you having to specify an action. As someone states above though, if it has unique constraints on it nothing will happen anyway. And if you want all email addresses in a table to be unique there's no reason to specify it as unique in your column definition.
Most likely something like:
IF NOT EXISTS(SELECT * FROM myTable WHERE Email=#Email) THEN INSERT INTO blah blah
That can be rolled into one database query.
A slight modification/addition to naeblis's answer:
INSERT INTO table (email) VALUES (email_address)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)
This way you don't have to throw email=email_address in there and you get the correct value for LAST_INSERT_ID() if the statement updates.
Source: MySQL Docs: 12.2.5.3
MySQL offers REPLACE INTO http://dev.mysql.com/doc/refman/5.0/en/replace.html:
REPLACE works exactly like INSERT,
except that if an old row in the table
has the same value as a new row for a
PRIMARY KEY or a UNIQUE index, the
old row is deleted before the new row
is inserted.
I'm not sure if I got it, but what about a
try {
mysql_query($sql);
}
catch(Exception $e) {
}
combined with an unique field index in MySQL?
if it throws an exception then you know that you got a duplicated field.
Sorry if that don't answer your question..
If the email field was the primary key then the constraints on the table would stop a duplicate from being entered.

Categories