MySQL - make row and update if already exists - php

I have table with 4 columns: Date, John, Frank, Anthony
I want to make a form which can be filled in by these 3 people everyday and store these values in the database. When John fills in the form today, a new row should be created with the date of today, with his value in the database. When Frank fills in the form 1 hour later (so the same day) his values should also be inserted in the database but in the same row because there's already a row with today's date. But when Anthony fills in the form tomorrow, a new row should me created with the date of tomorrow.
So in short: the program checks if anyone has already filled in the form today. If yes: it just adds the value to the existing row of today in column of the person who filled it in. if not: it makes a new row with the date of today.
I already wrote this code, but the problem is that it makes a new row everytime someone fills in the form, and there should only be a row created if $person is the first one to fill in the form on that day.
$sql = "INSERT INTO table (Date, $name) VALUES (CURDATE(),'$values')";

First make sure that the Date field is a primary or unique key.
Then you can use ON DUPLICATE KEY UPDATE
$sql = "INSERT INTO table (Date, $name) VALUES (CURDATE(),'$values')
ON DUPLICATE KEY UPDATE $name='$values'";
But you really should check for prepared statements in your language (PDO in case of PHP) to prevent SQL injections.

You should change your table.
Instead of a column for each person make a name column so you have:
Date | Name | Values
Make date and person the primary key:
ALTER TABLE 'table' ADD PRIMARY KEY (Date,Name)
Then insert like this:
INSERT INTO table (Date,Name,Values) VALUES (CURDATE(),'$name','$values') ON DUPLICATE KEY UPDATE Values='$values'

Try using REPLACE INTO instead of using INSERT INTO.

EDIT
I just re-read the question - the OP wants to overwrite the data if the user re-submits the form - first time I read it I thought they wanted to keep the original data
An alternative [if you only wanted to keep the original data only], would be using insert ignore : see this answer for a comparison between insert ignore and on duplicate key update: "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
Though you should probably change the table design to be 'date', 'person', 'data' as suggested in another answer

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

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.

"insert on duplicate update" still inserts duplicates

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.

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