仅在用户的ip是唯一的时才执行查询

I would like to save data to database only once per user, based on his/her IP address. I have a database with the url, date, time and ip list. How can I check if ip already exist and if not - insert data to database, otherwise do nothing? Here's my code so far:

<Check if IP already exists in the database - if no - insert:>


$query = "INSERT INTO link (url, date, time, ip) VALUES ('$ref','$date','$time', '$someip')";
mysql_query($query) or die('Error, insert query failed');

}
else {

echo 'This ip already exists';

}

Query your database for a row with a matching ip. You can then use mysql_num_rows to determine how many rows were returned.

$sql = "SELECT * FROM link WHERE ip = '127.0.0.1' LIMIT 1";
$query = mysql_query($sql);

if(mysql_num_rows($query) == 0)
{
  // IP  does not exist, proceed with insert.
}

127.0.0.1 should obviously be a variable. You can get a users ip with $_SERVER['REMOTE_ADDR'].

Put an unique index on the ip column. A fault will be returned if a duplicate is inserted. This way you don't need to execute an extra query on the database. Just make sure the error you get back is handled in a correct way (or just ignore the error).

CREATE UNIQUE INDEX name_of_index ON tablename (columns_to_index);

Create a unique index on your column:

CREATE UNIQUE INDEX ix_link_ip ON link (ip)

and check for the errors on insert:

$query = "INSERT INTO link (url, date, time, ip) VALUES ('$ref','$date','$time', '$someip')";
$res = mysql_query($query);
if (!$res) {
        if (mysql_errno() == 1062) /* unique key violation */
                die('This IP already exists');
        else
                die(mysql_error());
}


}