Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

sql - preventing duplicate row insertion in php/mysql

how do you prevent the entry of duplicate records in php mysql? validating input before insertion to the table.

i am currently building a user registration section for my website but want to present them with an error if a duplicate username or email address is found in the database.

EDIT
This is what I have to far to insert rows... how would I implement both these answers here:

  <?php
        if (array_key_exists('confirm',$_POST)) {

                $Cuser = $_POST['Cuser']; 
                $Cemail = $_POST['Cemail']; 
                $Cpassword = $_POST['Cpassword'];
                $md5password = md5($_POST['Cpassword']);

                mysql_query("INSERT INTO tbl_users (`username`,`email`,`password`)
VALUES ('$Cuser', '$Cemail', '$md5password')"); 

                echo "Thank you. The user <b>".$Cuser."&nbsp;(".$Cemail.")</b> has been successfully added to the database.<p>

                <a href='myaccount.php' class='form'>Return</a>";       

                exit;
        }
        ?>

I'm guessing that I could implement it all in an if...else statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Define unique constraints for the username and email columns:

ALTER TABLE your_table ADD CONSTRAINT uk_username UNIQUE (username)
ALTER TABLE your_table ADD CONSTRAINT uk_email UNIQUE (email)

If the value attempting to be insertered or updated already exists in the table, MySQL will return an error stating the query violates the appropriate unique constraint (possibly both). It's up to you to setup PHP to handle this gracefully.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...