RE: [PHP-DB] True/false value of SELECT statement. -- detecting if a record exists

From: Date: Mon, 31 Jul 2000 22:08:49 +0000
Subject: RE: [PHP-DB] True/false value of SELECT statement. -- detecting if a record exists
References: 1  Groups: php.db 
Request: Send a blank email to php-db+get-1656@lists.php.net to get a copy of this message
I do things like this in mySQL, I'm sure the logic is the same in Postgress... switch ($action) { case "Add" : if ($errstring == "") { $duplicatesFound = false; //assume there are no dupes to begin with $duplicateResult = mysql_db_query("mydb", "SELECT client_id, client_name FROM Client_Table WHERE client_name LIKE '%".$client_name."%' ORDER BY client_name DESC"); if (!$duplicateResult) { echo "<FONT COLOR=#00FF00><PRE>".mysql_errno().": ".mysql_error()."</PRE></FONT>\n"; exit; } $duplicateRows = mysql_num_rows($duplicateResult); if ( $duplicateRows > 0 ) { $duplicatesFound = true; // We found some duplicates so dump them out but leave the existing fields populated $button_label = "Proceed"; break 1; // break out two levels to bypass the "Proceed" that is below here... } } case "Proceed" : if ( $errstring == "" ) { $sql = "INSERT INTO Client_Table VALUES (null,'$client_name','$client_contact')"; //echo $sql."<BR>"; $result = mysql_db_query("mydb", $sql); if (!$result) { echo "<FONT COLOR=#FF0000>Add ".$client_name."<P><PRE>".mysql_errno().": ".mysql_error()."<BR></PRE></FONT>\n"; exit; } // successful post so clear the variables and get ready to do it again! $client_id = ""; $client_name = ""; $client_contact = ""; $client_phone = ""; } break; another fun trick is to set the field as UNIQUE, then you can just do... $sql = "INSERT INTO Product_Table VALUES (null,'$product_name', $product_sku_id)"; $result = mysql_db_query("mydb", $sql); if (!$result) { if (mysql_errno() == 1062) { echo "<P><FONT COLOR=#FF0000><B>".$product_sku_id."</B> already exists in the database</FONT><BR>\n"; $duplicateSKUResult = mysql_db_query("mydb", "SELECT product_name, product_sku_id FROM Product_Table WHERE product_sku_id='".$product_sku_id."' ORDER BY product_name, product_sku_id DESC"); if (!$duplicateSKUResult) { echo "<FONT COLOR=#00FF00>While Checking for the Duplicate SKU:<PRE>".mysql_errno().": ".mysql_error()."</PRE></FONT>\n"; exit; } $duplicateSKURows = mysql_num_rows($duplicateSKUResult); } else { echo "<FONT COLOR=#FF0000>Insert Failed for ".$product_name."<P><PRE>".mysql_errno().": ".mysql_error()."<BR></PRE></FONT>\n"; exit; } } > I'm using a SELECT statement in my PostgreSQL db to test if a record has > already been added. If it hasn't, then obviously there is no > result. How do > I set up an if/else structure to handle this? > > I've been trying: > > if (!$resultSet) { > > add the record > > } else { > > don't add it (but i need this else block because i'm using it to add > something to another part of the db) > > } > > ... but this doesn't seem to work.

« previous php.db (#1656) next »