Update if record already exists for todays date - php

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']\'");}

Related

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

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

Insert distinct records in the table while updating the remaining columns

This is actually a form to update the team members who work for a specific client, When i deselect a member then it's status turns to 0.
I have a table with all unique records. table consists of four columns -
first column is `id` which is unique and auto_incremented.
second column is `client_id`.
third column is `member_id`. (these second and third columns together make the primary key.)
fourth column is `current` which shows the status (default is 1.).
Now i have a form which sends the values of client_id and member_id. But this forms also contains the values that are already in the table BUT NOT ALL.
I need a query which
(i) `INSERT` the values that are not already in the table,
(ii) `UPDATE` the `current` column to value `0` which are in the table but not in the form values.
here is a screenshot of my form.
If (select count(*) from yourtable where client_id = and member_id = ) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
First of all check if the value exists in the table or not, by using a SELECT query.
Then check if the result haven't save value so it will be inserted, else show an error .
This would be a great time to create a database stored procedure that flows something like...
select user
if exists update row
else insert new row
stored procedures don't improve transaction times, but they are a great addition to any piece of software.
If this doesn't solve your problem then a database trigger might help out.
Doing a little research on this matter might open up some great ideas!
Add below logic in your SP
If (select count(*) from yourtable where client_id = <value> and member_id = <value>) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
if you want simple solution then follow this:
*) use select with each entry in selected team.
if select returns a row
then use update sql
else
use insert sql.
In your case member_id & client_id together makes the primary key.
So , you can use sql ON DUPLICATE KEY UPDATE Syntax.
Example:
$sql="INSERT INTO table_name SET
client_id='".$clientId."',
member_id='".$member_id."',
current='".$current."'
ON DUPLICATE KEY
UPDATE
current = '".$current."'
";
In this case when member_id & client_id combination repeats , it will automatically executes update query for that particular row.

prevent a value repeating in the same day

i am trying to develop php simple script that can be entered records like this: (mysql is my db engine)
id (auto increment, primary key)
StudentName
StudentNumber
ClassName
Grade
ScreeningDate (mm/dd/yyyy)
etc.
now what I need is to prevent the StudentNumber to be entered in the same day, for example, if other user has entered it already, then a message says: this Number was already added for today...
In other words, i need before the insert, to check if the studentNumber is there, then give the message, otherwise, will add the row normally...... hence, next day, it is okay, they can add same studentNumber again like yesterday.... something like PrimaryKey but only for today! how is this possible?
Create a unique compound index on (ScreeningDate, StudentNumber). Then INSERT operations that would place duplicates into your table will fail with duplicate-key errors.
You will need to detect this duplicate-key situation in your PHP code and return the appropriate message to the user who attempted to insert the dup. The INSERT statement will return an error.
Or, you can use INSERT ... ON DUPLICATE KEY UPDATE if you want to update the row if it already exists. Read this. http://dev.mysql.com/doc/refman/5.6/en/insert.html
To create the index, do this:
ALTER TABLE whatever ADD UNIQUE INDEX NoDailyDups (ScreeningDate, StudentNumber)
This approach has the advantage that it works correctly, without explicit table locking, even on a very busy system. If two users happen to be racing to insert the first item for a particular student and day, one of them will win and the other will get the duplicate-key error.
Notice also that your table is slightly denormalized -- it contains slightly redundant data. You might want to create another table containing the columns StudentNumber and StudentName, and move the student names out of this table.
Do a select to get the specified student number on today's date like this:
SELECT * FROM table WHERE StudentNumber = 123 AND DATE(ScreeningDate) = CURDATE()
If any rows are returned, there's a record for this student number on today's date, otherwise you are free to insert. The DATE function extracts the date part of a date, i.e. the date month and year
This may not be efficient but you can fetch all the rows of current date first:
SELECT StudentNumber, ScreeningDate FROM tablename WHERE StudentNumber = '22' AND ScreeningDate = 'mm/dd/yyyy';
And don't add(insert query) if the above query returned more than 0 rows(it will be one generally).

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.

PHP - MYSQL - insert on duplicate key AND(?)

Is it possible to connect the duplicate key to another statement.
I just picked some integers (4=4) for the example. In the actuall code I am trying to compare two dates and only if the date in the database row is bigger than the php generated date AND duplicated key it should update unj to 7.
from this:
$sql="INSERT INTO mutable (hid, xsn, unj, for, datetime)
VALUES ('$hid', '$xsn', '$unj', '$for', now()) ON DUPLICATE KEY UPDATE unj=7";
to this:
$sql="INSERT INTO mutable (hid, xsn, unj, for, datetime)
VALUES ('$hid', '$xsn', '$unj', '$for', now()) ON 4=4 AND DUPLICATE KEY UPDATE unj=7";
( ON 4=4 AND ) added.
But this is not working. Is there any way to archive this?
Thank you.
edit: I know I could archive this with using SELECT and then INPUT or UPDATE but I need more efficient code.
INSERT INTO mutable (hid, xsn, unj, `for`, datetime)
VALUES ('$hid', '$xsn', '$unj', '$for', now())
ON DUPLICATE KEY UPDATE unj = IF(datetime > VALUES(datetime), 7, unj)
I tested this and it works.
The VALUES(datetime) refers to the value you tried to insert into the datetime column. It's a convenient way to repeat the value in your ON DUPLICATE KEY UPDATE clause without having to write it twice in the query.
If the condition in IF() returns false, then the default is to set unj = unj which means a no-op.
PS: for is a MySQL reserved word, so it needs to be delimited. It would be simpler to avoid that column name.

Categories