How to avoid duplicated entry when adding on database [duplicate] - php

This question already has answers here:
MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?
(3 answers)
Closed 10 months ago.
how can i avoid to add duplicated entry in my database that is based on date? where instead of inserting again the duplicate entry, i will just update the old data to be deactivated and insert the new duplicate entry.
Here is the structure
Price table
id date_created Value is_active
1 2019-10-01 1:00:00 25 0
2 2019-10-05 2:00:00 30 0
but imagine that the user added a duplicated data again for the Price table which is like this.
2019-10-05 3:00:00
so what i want to do is to update the old entry that has the same date of the user entry to be is_active 1 and insert the new entry.
is there a way to do this? doing this on PHP is really complicated for me because of the use of looping, but i think there is a way in MYSQL which i cant figure it out.

You could first try to fetch the entry with the specific date and then update, otherwise insert.
You should also set the date_created column to UNIQUE.

As in the official documentation:
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be
inserted would cause a duplicate value in a UNIQUE index or PRIMARY
KEY, an UPDATE of the old row occurs.
In your case I suggest to you to do these steps:
create a new column date_time_created as DATETIME
convert date_created as DATE and save in it only the date
e.g. $date = date('Y-m-d', strtotime($yourDateTime));
set date_created as UNIQUE index:
CREATE UNIQUE INDEX date_created ON Price(date_created);
INSERT INTO Price
(Value, date_created, date_time_created, is_active)
VALUES
('$theValue', '$date', '$dateTime', 1)
ON DUPLICATE KEY UPDATE is_active = 0
The conversion of date_created in DATE and the creation of date_time_created as DATETIME are necessary because is useless in your case to make a DATETIME unique because you need to check the value only by date. This also improve the readability and maintenance of your script.

Query the table and check if that date exists and is_actice = 1 and use the results to first update existing row then insert

Related

How can i order by last update row

I have one Sql Query to get all the informations from my table.
I created an list using an foreach.
And i want to order this list, by the last updated row.
Like this
$query - "SELECT * FROM table ORDER BY last_updated_row";
//call Query here
And when i updated a certain row, i want to put this row on the top of the list
I heard about time_stamp, can i use time_stamp for that?
how can i do that?
Thanks
Assuming your using MySQL your table needs to be like this
CREATE TABLE table (
last_updated_row TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
That will give the row a create time stamp and update it on each update statement which effects the row
http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
You can use just about any date/datetime/timestamp column in a table to sort by if needed. The only catch is you need to actually have it in the table.
Any of the above will allow sorts by ascending/descending order, but need to be maintained when inserting/updating a row.
Assuming you have the following structure:
table - someTable
id someVale updateTime
1 54634 ......
2 65138 ......
3 94141 ......
4 84351 ......
It doesn't matter what type of column updateTime is - whether it is a date, a datetime, a timestamp, a simple order by updateTime will work.
But you need to make sure that each insert/update you make to that row updates the column so that the sort will be true.

Date when record was created in mysql datatabase

I have table in which I have birthdate , age location and Score and I want to retrieve the count of number of records created between two dates where score is not null and there is no time stamp field.
How can I do it if there is no time stamp field.
Is there any meta data and if it is , how can I run the query?
try a query like this:
SELECT COUNT(*)
FROM TABLE_NAME
WHERE BIRTHDATE BETWEEN 'DATE1' AND 'DATE2'
AND SCORE IS NOT NULL AND TIMESTAMP IS NULL;
Add a column timestamp to the existing table, with default value as NULL, and query the above statement, it should work.
Whenever you add a column, to a table already having records, the corresponding values are blank for that new column, for existing records.
Add a timestamp to your tables
Echoed here as other users have noted.
Because you have no date reference field in the database, you can't pull out records that match one or that are between two dates.
Your best bet from here on in, is to add a date field and then make sure when data is written to the DB, you insert a date/datetime using mysql now() function. There are a few different ways to achieve it, but this is probably the easiest:
mysql_query("
INSERT INTO users (first, last, whenadded)
VALUES ('$first', '$last', now())
";

Avoid entering duplicate entries based on date, without using select statement

I am running a insert statement to insert data, but I want to check for any duplicate entries based on date and then do an entry.
All I want is if today a user enters product_name='x', 'x' is unique so that no one can enter product name x again today. But of course the next day they can.
I do not want to run a select before the insert to do the checking. Is there an alternative?
You can either use
1. Insert into... on duplicate update
2. insert.. ignore
This post will answer your question
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
You can use the mysql insert into... on duplicate update syntax which will basically enter in a new row if one isn't there, or if the new row would have caused a key constraint to kick in, then it can be used to update instead.
Lets say you have the following table:
MyTable
ID | Name
1 | Fluffeh
2 | Bobby
3 | Tables
And ID is set as the primary key in the database (meaning it CANNOT have two rows with the same value in it) you would normally try to insert like this:
insert into myTable
values (1, 'Fluffster');
But this would generate an error as there is already a row with ID of 1 in it.
By using the insert on duplicate update the query now looks like this:
insert into myTable
values (1, 'Fluffster')
on duplicate key update Name='Fluffster';
Now, rather than returning an error, it updates the row with the new name instead.
Edit: You can add a unique index across two columns with the following syntax:
ALTER TABLE myTable
ADD UNIQUE INDEX (ID, `name`);
This will now let you use the syntax above to insert rows while having the same ID as other rows, but only if the name is different - or in your case, add the constraint on the varchar and date fields.
Lastly, please do add this sort of information into your question to start with, would have saved everyone a bit of time :)

mysql update if some values exists otherwise create a new entry [duplicate]

This question already has answers here:
MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?
(3 answers)
Closed 10 months ago.
I have a table rating with these fields rate_id, game_id, rating, ip. Let suppose that these fields has the following values 1,130,5,155.77.66.55
When a user try to vote for a game, I want with mysql to check if he has already vote for this game so mysql will check if ip and game_id already exists, if they exists then mysql will update the value of rating otherwise will create a new entry.
What is a efficient way to do this?
Create unique index that covers ip + game_id. After that you can use INSERT ... ON DUPLICATE KEY UPDATE statement.
So the total query will be something like
INSERT INTO rating (rate_id, game_id, rating, ip) VALUES (1,130,5,'155.77.66.55')
ON DUPLICATE KEY UPDATE rating = 5
MySQL allows an on duplicate key update syntax for INSERT. So if you set your key to be game_id, user_id (or whichever way you identify the user) then you can use INSERT...on DUPLICATE KEY UPDATE which will do just that:
http://dev.mysql.com/doc/refman/5.5/en/insert.html
You could also take a look at REPLACE INTO. Maybe not for this project but for future reference:
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
from: dev.mysql.com
// check to see if exist
$sql = "SELECT ip FROM rating WHERE ip=$ip && game_id={$game_id}";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(isset($row['ip'])){
mysql_query("UPDATE HERE");
}else{
mysql_query("INSERT HERE");
}

Update if record already exists for todays date

Is there is an easy way to change the following query to check to see if a record already exists for todays date if it does to update it with the newest count value.
mysql_query("INSERT INTO daily_record (PageID, count)
VALUES (".$array['page_id'].",".$array['count'].")");
The column I want to check is a CURRENT_TIMESTAMP field (record_date - part of daily_record table) if a todays date exists for a pageID then an update needs to happen rather than a new insert.
If someone can help that would be amazing!!!
Well if you build the daily_record table like this:
CREATE TABLE daily_record (
pageID INT,
record_date DATE,
count INT,
PRIMARY KEY (pageID,record_date),
INDEX idxPageID (pageID)
)
You could then use the command:
INSERT INTO daily_record (
pageID,record_date,`count`
) VALUES (
1,'2011-03-31',32
) ON DUPLICATE KEY UPDATE `count`=32;
Obviously pageID/record_date/count would be supplied by the calling code. This effectively creates a record for the pageID/day with the given count, or if a record for the pageID/day already exists, then it sets the count to the supplied value.
Using the DATE column type prevents you getting free timestamping BUT that's not particularly useful for this table - the way you describe it - since you don't care about the hours/minutes/seconds.
The key here is the unique index created by the PRIMARY KEY... line. If it's uniqueness would be violated by an insert then an update on it can occur instead.
Best I can come up with is either use a select with if ... then to check for the existance ahead of time, or run the update statement first, check ##rowcount (records affected) and do an insert if it comes back with 0)
i.e. No.
[Edit - this is a little more complex than it seemed at first, because of the DATE thing.]
To UPDATE the record you MUST get the count that you want to update, so that requires you to use a SELECT first. But you need to select the records that are only for the current date.
Let's assume that you have done the code to get the current date into $today.
Then as Kendrick said,
$result=mysql_query("SELECT * from daily_record where PageID=\'$array['page_id']\' and date_field BETWEEN '$today'.' 00:00:00' AND '$today'.' 23:59:59'");
if (!$result)
{ mysql_query("INSERT into daliy_record (PageID,count} VALUES (\'$array['page_id']\',\'$array['count']\')"); }
else
{mysql_query("UPDATE daily_record (count) VALUES (\'$array['count']\') where PageID=\'$array['page_id']\' and date_field=\'$result['date_field']\'");}

Categories