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

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.

Related

How do I insert a piece of information to an already existing record?

I have an SQL Database setup with rows of data already there. How do I update just one column of one row by grabbing the id (appointmentspage.php?id=1")?
I already have written the code to input the data into the correct position table I want, but I am having trouble selecting the id too
if(isset($_POST["submit"]))
try{
$sql = "INSERT INTO appointments (Notes)
VALUES ('".$_POST["Notes"]."')";
I feel like = $_GET['id']; or WHERE appointments.ApptID = :id should be used, but I can't fathom it.
Currently the 'Notes' column in my SQL table gets an input, but it creates a new empty row with only that data added. I want to select an existing row/entry and add the Notes to that.
On my site I have a set of examples for the basic use cases, you are welcome to check them out.
Your case would be UPDATE query using PDO.
First of all, "insert into an existing record" is called UPDATE. You need to check out your SQL textbook.
And yes, you need something like ApptID = :id in your query. However personally I prefer simple ? marks
So it should be something like
$sql = "UPDATE appointments SET notes=? WHERE ApptID=?";
$stmt= $dpo->prepare($sql);
$stmt->execute([$notes, $id]);
Note three shouldn't be any try or catch stuff around.
You need to define ApptID field as Primary Key with auto-increment field in database define. In MySQL, a primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a NULL value. A table can have only one primary key.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
After that you can use that ApptID for update your existing data using Update query in MySQL

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

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.

Insert but ignore if duplicate AND set a value different if exist in another table

I'm trying my make an invitation system together with the Facebook PHP APK. What I basically want is when you have invited your friends, Facebook redirects back to your website with an array containing userIDs from friends that the user invited. I wish to loop through them and insert the invitations into a database. The looping and all is already under control but the database query isn't.
This is what my current query looks like:
SELECT `iID` FROM `invitations` WHERE `iSender` = 'SENDER' AND `iReceiver` = 'RECEIVER';
If that returns zero rows I process this query:
INSERT INTO `invitations` (`iSender`, `iReceiver`) VALUES ('SENDER', 'RECEIVER');
And then I check if they're already signed up to my website:
SELECT `uID` FROM `users` WHERE `uOAuthID` = 'RECEIVER';
If it returns more then 1 row I run the following and final query:
UPDATE `invitations` SET `iProcessed` = 1 WHERE `iReceiver` = 'RECEIVER';
So basically this is how the process is currently shaped:
If the user hasn't already has been invited by the inviter we insert the invitation into the database.
Then we check if the invited user already is signed up.
If he is signed up we update the invitation and say that it already has been processed.
I guess there's a better and faster method to do this with just maybe 1 or 2 queries. I've tried using INSERT IGNORE and ON DUPLICATE but that just gave me errors and gave up.
I hope that you understand what I'm looking for. Thank you all for your time!
There are to thing that suite your needs:
INSERT ... ON DUPLICATE KEY UPDATE Syntax:
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, an
UPDATE of the old row is performed. For example, if column a is
declared as UNIQUE and contains the value 1, the following two
statements have identical effect:
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE
c=c+1;
INSERT IGNORE:
If you use the IGNORE keyword, errors that occur while executing the
INSERT statement are ignored. For example, without IGNORE, a row that
duplicates an existing UNIQUE index or PRIMARY KEY value in the table
causes a duplicate-key error and the statement is aborted. With
IGNORE, the row still is not inserted, but no error occurs.

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