识别用户MySQL和PHP的重复条目


Identify duplicate entry for user, MySQL & PHP

>我有一个提交表单,当用户尝试使用重复条目提交它时,它会返回MySQL错误#1062。例如,错误指出:

Duplicate entry 'graphics' for key 'name'

我想给用户一条自定义消息,解释(用简单的英语)他们收到错误的原因,以及导致错误的特定条目。例如:

"Graphics" is a duplicate entry and should not be used. Please remove it and resubmit the form."

键将始终是"名称",但重复条目本身通常会有所不同。我需要能够从生成的 MySQL 错误中提取该特定值,然后将我的自定义消息包装在它周围。怎么能做到这一点呢?

您可以尝试进行简单的错误检查,在发生 mysql 错误时向用户显示您的错误消息。你可以尝试这样的事情:

$rows = mysql_query("SELECT `name` from `tbl` WHERE `name` = 'graphics';");
if(mysql_num_rows($rows) > 0){
    echo '"Graphics" is a duplicate entry and should not be used. Please remove it and resubmit the form.';
}else{
    insert...
}

如果要插入的项目事先存在,则可以在输入任何数据之前先检查表。

其次,您可以使用if else循环根据错误打印自定义消息喜欢

      $check_exists = // runs the code here to check if the entry graphics already exists for the existing name
     if ($post['name'] == ''){
     // error message for blank entry 
     }elseif($check_exists == true) {
   // custom error mesage for duplicate entry 
    }else {
  // submit the form here
    }