如何避免在PHP中重复

时间:2014-02-06 03:32:24

标签: php mysql sql

我是php的新手。我现在正在创建一个类似登录页面的简单程序。请你帮我做我的编码,我有一个名为user的mysql表,它有3列userid,email和密码。我的主要是userid,它是一个自动增量。我怎么能有代码,列电子邮件应该没有重复或没有相同的电子邮件。我已经有避免空字段的代码我现在不知道如何处理重复.. 这是我的示例代码:

<?php   
        if(isset($_POST['submit'])){
            $dbhost = 'localhost';
            $dbuser = 'root';
            $conn = mysql_connect($dbhost, $dbuser);
            mysql_select_db('dtr');
            if(! $conn ){
                die('Could not connect: ' . mysql_error());
            }

            if(! get_magic_quotes_gpc() ){
                $email = addslashes ($_POST['email']);
                $password = addslashes ($_POST['password']);
            }
            else{
                $email = $_POST['email'];
                $password = $_POST['password'];
            }   
                //validation
            if($email == ''){
                echo "empty ang email" ?></br><?php ;
                return false;
            }   
            if($password == ''){
                echo "kailangan may password ka\n" ?></br><?php ;
                return false;
            }
---------------------->//select * table where username=user
            {   
        $sql = "INSERT INTO user "."(email, password) "."VALUES('$email','$password')";
        $retval = mysql_query( $sql, $conn );
            }
            if(! $retval ){
                die('Could not enter data: ' . mysql_error());
            }
                echo "Entered data successfully\n";
                mysql_close($conn);
        }
            else
                {
            }
    ?>

帮帮我PLZ ..

2 个答案:

答案 0 :(得分:3)

你可以尝试:

$sql = "SELECT userid from users WHERE email = ". $_POST["email"];
if (mysql_num_rows(mysql_query($sql, $con)) >= 1)
{
    echo "That email you provided seems to be already used";
    return;
}

请关于使用不同的db扩展,因为从PHP V开始不推荐使用mysql 5.5。它将通过绑定和准备好的语句为您提供更好的安全功能。

答案 1 :(得分:0)

简单地使用它,我认为应该给你帮助:

$name = $_POST[name];
$pass = $_POST[pass];

$user = "SELECT * from users WHERE email = '".$email."'";
$result = mysql_query($user);
if(mysql_num_rows($result)>0){
return "$result";
}
else{
mysql_query("INSERT INTO users(email, pass) VALUES ('$email', '$pass')");
}