lime icon

Phosphorus and Lime

A Developer's Broadsheet

This blog has been deprecated. Please visit my new blog at klenwell.com/press.
PHP: mysql_is_unique
Given table, column name, and value (with option database name argument) will tell you whether that value is currently in the database table. Useful for user management systems.

/* Fx mysql_is_unique
******************************/
function mysql_is_unique($table, $col_name, $value, $db_name='default')
{
// *** DATA

# internal
$SQL['select_unique'] = '';


// *** MANIPULATE

// default db
if ( $db_name == 'default' )
{
if ( defined('DB_NAME') )
{
$db_name = DB_NAME;
}
else
{
trigger_error('database not defined', E_USER_WARNING);
return FALSE;
}
}

// sanity checks

# column name
if ( empty($col_name) )
{
trigger_error("empty column name", E_USER_WARNING);
return FALSE;
}

# value
if ( empty($value) )
{
trigger_error("empty value", E_USER_WARNING);
return FALSE;
}

# table
if ( !mysql_is_table($table, $db_name) )
{
trigger_error("table [$table] not found", E_USER_ERROR);
return FALSE;
}

// open DB
$link = open_db($db_name);

// sanitize input
$value = mysql_sanitize_input($value, $link);

// mysql query
$SQL['select_unique'] = "SELECT `$col_name` FROM `$table` WHERE `$col_name` = '$value'";

// result
$_sqlr = mysql_query($SQL['select_unique'])
OR trigger_error('MySQL error number '.mysql_errno().': '.mysql_error());

// close db
close_db($link);


// *** RETURN

# is not unique
if ( mysql_num_rows($_sqlr) > 0 )
{
return FALSE;
}
# is unique
else
{
return TRUE;
}

} # end Fx
/******************************/