PHP Aiuto su query php

Stato
Discussione chiusa ad ulteriori risposte.

XxidroxX

Utente Gold
22 Aprile 2011
609
64
40
226
ciao a tutti io ho una tabella:
id name pid

Io vorrei eseguire una query che inserisco i valori nella tabella se non esiste già un valore uguale.
Come faccio?
 
lo so però così devo fare due query una per contare e l'altra per inserire. Non c'è un modo più veloce. Avevo sentito parlare di WHERE NOT EXIST
 
ho provato a fare questa query:
Codice:
INSERT INTO ".FORUMS." (forum_name, ally_id) VALUES ('".$forumname."', '".$allyid."') WHERE NOT EXISTS (SELECT * FROM ".FORUMS." WHERE `forum_name` = '".$forumname."' AND `ally_id` = '".$allyid."');
ma mi da errore:
Codice:
SQL Error: You have an error in your SQL syntax; check the manual that  corresponds to your MySQL server version for the right syntax to use  near 'WHERE NOT EXISTS (SELECT * FROM uni1_forums WHERE `forum_name` =  'sssss' AND `al' at line 1
 
Scusami ma fai cosi allora no?

Codice:
$query = mysql_query("SELECT COUNT(*) FROM tabella WHERE ...condizione...") or die(mysql_error());

if(mysql_result($query,0) > 0)
         //valori esistenti
 else
       //inserisci i valori

Non ti complicare la vita con centinaia di query quando puo essere facilmente fatto con 2 righe in piu
 
ho capito però così creo due query e appesantisco tutto quando si fa facilmente con NOT EXISTS
Allora prova a risolvere l'errore di prima cosi

Codice:
("INSERT INTO ".FORUMS." (forum_name, ally_id) VALUES ('".$forumname."', '".$allyid."') WHERE NOT EXISTS (SELECT * FROM ".FORUMS." WHERE ".FORUMS.".forum_name = '".$forumname."' AND ".FORUMS.".ally_id = '".$allyid."')");
 
Dubito ti possa farlo in una sola query e credo che NOT EXISTS funzioni solo con SELECT. Casomai prova a smanettare con questa creata per access:

Codice:
PARAMETERS [@NewValue] Text ( 255 ) ;
INSERT INTO MyTable ( Field )
SELECT DISTINCT [@NewValue] FROM MyTable
WHERE
(SELECT TOP 1 U.Field FROM MyTable U
WHERE UCase(Trim([@NewValue])) = UCase(Trim(U.Field))) IS NULL ;
 
ti costa tanto fare così?
Codice:
//stringa database
//si suppone che tu abbia già dichiarato una variabile che ha registrato l'email attraverso get o post;
$mail = mysql_query("SELECT * FROM users WHERE mail = $valore_input");
$row = mysql_num_rows($mail);

if ($row == 0) {
inserisci l'utente nel database
}
else
{
dai l'errore
}
 
ti costa tanto fare così?
Codice:
//stringa database
//si suppone che tu abbia già dichiarato una variabile che ha registrato l'email attraverso get o post;
$mail = mysql_query("SELECT * FROM users WHERE mail = $valore_input");
$row = mysql_num_rows($mail);

if ($row == 0) {
inserisci l'utente nel database
}
else
{
dai l'errore
}
La soluzione è gia stata proposta e ha risolto da se, inoltre è meglio fare direttamente un count nella query e ricavarne il valore
 
Stato
Discussione chiusa ad ulteriori risposte.