mysql phpmyadmin用户输入COMPARE数据库

时间:2013-08-23 16:34:14

标签: php mysql

大家好我是php和mysql的新手,我目前正在尝试查看用户输入和用户名,如果在数据库中已存在相同的用户名,则与用户输入$ email相同。

我有以下代码,我尝试使用一条回路并将用户输入与数据库中的提取行/数据进行比较。我能够验证它到达的地方 line echo $ email。“COMPARE”。$ result2;是两个相同,但它传递条件$ email == $ result2其中result2是从数据库中获取电子邮件。你能指点我有什么不对吗?提前谢谢。

$extract= mysql_query("SELECT * FROM users");
$resultq = mysql_num_rows($extract);
while($row= mysql_fetch_array($extract))
{

    $result = $row['username'];
    $result2 = $row['email'];

    echo $email."COMPARE".$result2;

    if($username == $result) 
    {
         echo "<script type=\"text/javascript\">alert('Username Already Taken')</script>";
         echo "<meta http-equiv=\"refresh\" content=\"0;url=6signup.html\" />";
         break;

    }
    else if ($email == $result2)
    {
         echo "<script type=\"text/javascript\">alert('Email Already Registered')</script>";
         echo "<meta http-equiv=\"refresh\" content=\"0;url=6signup.html\" />";
         break;
    }
    else
    {
        //continues to execute the loop until no more to fetch
    }

1 个答案:

答案 0 :(得分:1)

我会使用不同的方法在SQL查询中进行搜索。 在这种搜索中,SQL更好(并且性能更好)。

此查询不需要while循环:

SELECT *
FROM users
WHERE username = '<input username here>'
OR email = '<input email here>'

如果您收到结果,则表示用户名或电子邮件地址已经注册。使用if语句检查它是用户名还是电子邮件地址。

  

Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

完整的PHP代码将是这样的(对于PDO):

// Database connection
// -------------------
// I usually put this in a seperate file and include it.
try {
    $dbconn = new PDO('mysql:dbname=database;host=localhost', 'username', 'password');
} catch (PDOException $e) {
    die('Connection failed: ' . $e->getMessage());
}

// Prepare statement
// -----------------
// Build query using question mark parameters
$sql = "SELECT * FROM users WHERE username = ? OR email = ?";
// Create prepared statement
$sth = $dbconn->prepare($sql);

// Execute statement
// -----------------
// The parameters are automatically changed into your input data
$sth->execute(array($username, $email));

// Put all affected rows in $result (array!)
$result = $sth->fetchAll();

// Check array contents
// --------------------
if (count($result) > 0) {
    // Loop through results
    foreach ($result as $row) {
        if ($username == $row['username']) {
            echo "<script type=\"text/javascript\">alert('This username is already taken!')</script>";
            echo "<meta http-equiv=\"refresh\" content=\"0;url=6signup.html\" />";
        } else { // If username doesn't match, it has to be the e-mailaddress
            echo "<script type=\"text/javascript\">alert('This e-mailaddress has already registered!')</script>";
            echo "<meta http-equiv=\"refresh\" content=\"0;url=6signup.html\" />";
        }
    }
} else {
    /* Code to execute when not registered yet */
}