$Link= mysql_connect("localhost", "root", "", "");
query = mysql_query($Link,"SELECT col_name FROM table_name WHERE col_name='$val'");
$num=mysql_num_rows($query);
if($num==0){
$query1 = mysql_query($Link,"INSERT INTO table_name(col_name)VALUES('$val')"); )
}
There will be multiple calls to query at same time. I used this method to avoid multiple insertion, but sometimes multiple rows are inserted.Please help me. Thanks in advance.
thanks for your help..
I m not calling this code in loop but multiple calls at same time from different users are made.
mysql_query syntax: resource mysql_query ( string $query [, resource $link_identifier = NULL ] )
$query1 = mysql_query("INSERT INTO table_name (col_name)VALUES('".$val."')");
Full code:
$Link= mysql_connect("localhost", "root", "", "");
$query = mysql_query($Link,"SELECT col_name FROM table_name WHERE col_name='".$val."'");
$num=mysql_num_rows($query);
if($num==0){
$query1 = mysql_query("INSERT INTO table_name(col_name)VALUES('".$val."')");
}
If there are multiple simultaneous requests to the web server(s) that host the PHP, the select could return no results for more than one of these requests, and then there may be multiple inserts due to each such request performing the insert.
If you are not running windows and have only one web server, you could synchronize access to this code using PHP's semaphores.
But even better, can you put a unique constraint on the value of this column in the table in mysql?
Though your code is correct and it should not insert again, but
You should add a unique key to your field and then use Insert Ignore
"INSERT IGNORE INTO table_name(col_name)VALUES('$val')"