0

I'm trying to make a database check in my webpage that will check to make sure two columns (first_name and last_name) are unique. In MySql I already have those two columns as UNIQUE.

I want to have this check performed on the webpage, and return an error message if a first_name and last_name are already listed in the table. ex. If Tom Jones is in the table already, an error will show up if Tom Jones is input into the form. My statement below checks for this uniqueness, but it checks across all rows in the table. I need it to check row by row. member_no is the primary key, and I thought about searching with this, however, I want to check each row for uniqueness and I don't have a specific number to search.

This is just on the website/form side, since the UNIQUE statement for first_name and last_name is already active on MySql.

Or is there a more direct way to check the uniqueness in the table?

This is my statement:

$command = "SELECT * FROM member_info";
$member_result = mysql_query($command);
$mdata = mysql_fetch_object($member_result);
if ($first_name == $mdata->first_name && $last_name == $mdata->last_name) {
$error_message = "The first and last names must be unique. ";
} 

This will check the table but will not discriminate between the rows. ex. if row 1 is Tom Jones, and row 2 is Bob Smith, and if I put into the form 'Tom Smith' the error will come back as not unique.

4

4 回答 4

1

如果first_name并且last_name位于多列UNIQUE索引中,那么您可以继续插入值。如果INSERTed 值已经在数据库中,那么您将收到一条错误消息,然后您可以从那里获取它。

要创建多列 UNIQUE 索引,您可以ALTER像这样创建表:

ALTER TABLE `member_info` ADD UNIQUE (`first_name`, `last_name`);

然后INSERT是这样的:

$sql = "INSERT INTO `member_info` (`first_name`, `last_name`) VALUES ('{$first_name}', '{$last_name}')";

不过,您应该首先确保$first_name并且$last_name是安全的。如果不是,那么您将有安全漏洞。

于 2013-05-16T22:04:46.577 回答
0
  1. 您可以使用 where 子句:

    select * from member_info where first_name = {$first_name} and last_name = {$last_name}

  2. 您可以乐观地尝试插入,然后对重复键消息做出合理反应。

于 2013-05-16T21:58:04.250 回答
0

不推荐使用第一个mysql_功能。使用mysqli.

首先,您要清理用户输入。我将从这一点假设$first_name$last_name是已清理的变量,可以在 MySQl 语句中使用。

$query = "SELECT COUNT(*) FROM `member_info` WHERE `first_name`='$first_name' AND last_name='$last_name'";
$member_result = mysqli_query($command);
$mdata = mysqli_fetch_assoc($member_result);

if($mdata['COUNT(*)'] > 0) {
    //user with that first and last name already exists
}
于 2013-05-16T22:11:21.870 回答
0

为了跟踪唯一的字符串值,我认为最通用的解决方案(但在某些情况下可能有点过分)是使用字符串值的散列维护另一列并向该列添加 UNIQUE 约束。修改记录数据时会产生开销;您还应该更新哈希值(可以使用触发器自动完成)。

请记住,字符列上的索引具有字节限制(此问题中也提到了问题和解决方案)。不过,对于短字符串,您可以使用 @sverri 提出的复合索引解决方案。

于 2013-05-17T17:55:34.580 回答