Evite la inserción múltiple, cuando la consulta de inserción se llama varias veces al mismo tiempo

$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.

Gracias por tu ayuda..

I m not calling this code in loop but multiple calls at same time from different users are made.

preguntado el 27 de noviembre de 13 a las 05:11

avoid use of mysql_* try to use mysqli_* us3.php.net/manual/en/book.mysqli.php -

3 Respuestas

mysql_query syntax: resource mysql_query ( string $query [, resource $link_identifier = NULL ] )

 $query1 = mysql_query("INSERT INTO table_name (col_name)VALUES('".$val."')");

Código completo:

$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."')");
}

respondido 27 nov., 13:05

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?

respondido 27 nov., 13:05

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')"

respondido 27 nov., 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.