Lucas
Lucas

Reputation: 159

Is it possible to make an insert or an update in the same sql query?

I have a question that seems easy but i failed to solve it by miself

i have this table with the statistics of a website visitors

+-----------------------------+
+ date        | visits        +
+-----------------------------+
+  2014-03-17 | 198           +
+  2014-03-18 | 259           +
+  2014-03-19 | 94            +                 
+-----------------------------+

My question is what will be the correct way to insert the data to the table.

Currently what i am doing is:

$date = date("Y-m-d");    

$result = mysql_query("SELECT Count(*) as count FROM table WHERE date = '$date'");
$row = mysql_fetch_array($result);
$count = $row['count'];

if($count > 0){
mysql_query("UPDATE table SET visits = visits+1 WHERE date = '$date'");
}else{
mysql_query("INSERT INTO table (`date`, `visits`) VALUES ('$date', '1');");
}

Is this the right way to update the table or is there a better one? Is it possible to update it only with one sql query, for example like this:

mysql_query("If row exists update table else insert");

I dont know if this is possible.

Thank you very much in advance! id be very grateful if you can help me on this.

Upvotes: 4

Views: 94

Answers (2)

Tun Zarni Kyaw
Tun Zarni Kyaw

Reputation: 2119

Yes, if your date is the key in the table

INSERT INTO `table`(`date`, `visits`) 
VALUES(`$date`, `1`)
ON DUPLICATE KEY UPDATE
`visits`=`visits`+1

Reference: MYSQL:: INSERT ... ON DUPLICATE KEY UPDATE

Note: you are using mysql_* functions those are deprecated (means outdated, no longer supported, no longer modified), so try to use mysqli_* or PDO.

Upvotes: 3

xkeshav
xkeshav

Reputation: 54016

TRY

INSERT INTO `tabelname`(`date`, `visits`) VALUES ($date,1) 
ON DUPLICATE KEY UPDATE `visits` = `visits`+1

note: must set date column as UNIQUE index

tip: do not use mysql keyword as column name (date)

Reference

Upvotes: 0

Related Questions