大家好,我是 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
}
最佳答案
我会使用不同的方法并在 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. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose 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 */
}
关于php - mysql phpmyadmin 用户输入比较数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18407734/