Prevent duplicates in database

前端 未结 4 1656
有刺的猬
有刺的猬 2021-01-25 16:45
$db->query(\"SELECT * FROM \".DB_PREFIX.\"users WHERE uid=\'\".$uid_id.\"\' AND login=\'ExpressCheckoutUser\'\");
                if ($db->moveNext())
                     


        
4条回答
  •  情话喂你
    2021-01-25 16:51

    If all you need is a single UNIQUE column, you can do something like:

    ALTER TABLE `users` ADD UNIQUE `lname`(fname);
    

    If you set a column to UNIQUE it will only make that column unique, so if you have two people, one named "John Smith" and another named "Jane Smith", a UNIQUE on the lname will cause the second to fail. If you set UNIQUE keys on both first and last name fields separately, then you will fail in either case of first or last names being the same.

    You will probably instead wish to add a compound key to enforce uniqueness across multiple fields combined. For this:

    ALTER TABLE `users` ADD UNIQUE `unique_key`(fname,lname);
    

    This would force a constraint in the database that would throw an error if you tried to create a duplicate record with the same first and last name.

    You can throw exceptions on error, and handle these higher up in your codebase, or you can instead just see that you have an error and choose to ignore it.

提交回复
热议问题