Re: multiple fields all unique?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



John W. Holmes wrote:

From: "Jas" <jason.gerfen@xxxxxxxxxxxx>



Has anyone every performed such a feat as to check for matching fields
before updating? And if so could you show me some code that used to
accomplish this. I have written my own but the if - else statements are
getting ridiculous.



Are the columns actually declared UNIQUE in your database? That's the first step. Then you can just do the update, and if it fails with a specific error, you know you've hit a duplicate.

The long way to do it is to just SELECT the data first, then update if there
are no matches

(assuming MySQL, here, but the concept is the same)

$query = "SELECT mac, ip FROM table WHERE mac = '{$_POST['mac']}' OR ip =
'{$_POST['ip']}'";
$result = mysql_query($query) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
   if($_POST['mac'] == $row['mac'])
   { echo "{$row['mac']} is already being used. "; }
   elseif($_POST['ip'] == $row['ip'])
   { echo "{$row['ip'] is already being used. "; }
}
else
{
   $query = "UPDATE table SET mac = '{$_POST['mac']}', ip =
'{$_POST['ip']}' WHERE hostname = '{$_POST['hostname']}'";
   $result = mysql_query($query) or die(mysql_error));
   echo "Record updated!";
}

If you want an example of the first (and better) method, let me know.

---John Holmes...



Yeah, I have never used a unique field for the database, and you are right it is a mysql db.
Jas


--
Jason Gerfen
Student Computing Group
Marriott Library
University of Utah
(801) 585-9810
jason.Gerfen@xxxxxxxxxxxx

"I'm not a robot like you. I don't like having disks crammed into me... unless they're Oreos, and then only in the mouth." ~Phillip J. Fry

--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux