Data exists on the update does not exist Insert data SQL statement
/*
In the MySQL tutorial website production we will encounter in order to save a little bit of resources to the database tutorial operations more simplistic, such as the data exist on the update does not exist to insert data SQL statements, the following we will use Insert on duplicate key update to the instance,
Grammar:
Insert [low_priority | delayed | high_priority] [IGNORE]
[Into] tbl_name [(Col_name,...)]
Values ({expr | default},...), (...),...
[on duplicate key update col_name=expr, ...]
Here we do an example according to the above statement
Create a data table IPs tutorial Tats
CREATE TABLE Ipstats (
IP varchar NOT NULL unique,
Clicks smallint (5) unsigned NOT null default ' 0 '
);
*/
$CN = mysql_connect (' 127.0.0.1 ', ' root ', ' root ');
mysql_select_db (' abc ', $CN);
$sql = "INSERT into ipstats values (' 192.168.0.1 ', 1) on duplicate key update clicks=clicks+1";
mysql_query ($sql) or Die (Mysql_error (' Insert data failed '));
Echo ' successful operation ';
We're using INSERT into on duplicate key update, so let's take a look at the way I used to
$sql = "SELECT * from Ipstats where ip= ' 192.168.0.1 '";
$query = mysql_query ($sql);
if (mysql_num_rows ($query))
{
mysql_query ("Update ipstats set clicks=clicks+1 where ip= ' 192.168.0.1 '");
}
Else
{
mysql_query ("INSERT into ipstats values (' 192.168.0.1 ', 1)");
}
From this point of view we are more complex, of course, there is a way to execute directly in SQL but also three steps to the following code
$sql = "if (select * from Ipstats where ip= ' 192.168.0.1 ') {
Update ipstats set clicks=clicks+1 where ip= ' 192.168.0.1 ';
} else {
INSERT into Ipstats (IP, clicks) VALUES (' 192.168.0.1 ', 1);
}";
mysql_query ($sql);
/*
Summarize:
After the above three kinds of MySQL data exist on the update does not exist to insert data SQL statement Instance code, you can draw insert into on duplicate key update is the most convenient and fast, where we are in the Web development is to choose the most suitable for the current application method to deal with the problem, All three of the above methods can be used for instance data insertion if the existence is to be updated, but the first is the best.
Site original tutorial, reprinted annotated Source http://www.111cn.nethttp://www.111cn.net/database/database.html
*/