Re: multiple fields all unique?

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

 



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

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