2

我正在尝试编写一个 PHP 函数来检查给定值是否在数据库的列中。该函数接受参数$userName,并且将在数据库的列中检查$link位置。这是我到目前为止所得到的:$userNameuserid$link

<?php  
/*This function checks to see if the username is already in use  
INPUT: the userName to check for and a link to the database  
OUTPUT: true if there are no other users registered with userName  
*/  
function isUnique($userName, $link)  
{  
    $result = !!mysqli_fetch_row(mysqli_query($link, 'SELECT `userid`  
    FROM `login`  
    WHERE `userid` = \''.$userName.'\''));  
    return $result;  
}  


echo '<html><head><title>testing</title><body>';  
$uName = $_POST['us'];  
$pass = $_POST['pa'];  

//database work  
$link = mysqli_connect("localhost:3306", "root", "");  
if(!$link)  
    die('Could not connect to MySQL: '.mysql_error());  
$db_selected = mysqli_select_db($link, 'Accounts');  
if(!$db_selected)  
    die('Can\'t use Accounts: '.mysql_error());  
echo '<br />Using Accounts database<br />';  
if(isUnique($uName, $link))  
{  
    echo 'username is unique!<br />';  
}  
else  
{  
    echo 'username is not unique!<br />';  
}  
mysqli_close($link);  

echo '</body></html>';  
?>

该页面总是说给定的用户名不是唯一的。

4

3 回答 3

1

试试这个:

function isUnique($userName, $link) {
    return !!mysqli_fetch_row(mysqli_query($link, "select `userid` from `login` where `userid`='".$userName."'"));
}

由于如果没有行则mysqli_fetch_row返回null,如果有则返回数组,因此转换为布尔值将告诉您是否存在行。

于 2013-01-14T18:23:55.973 回答
0
$userName = mysqli_escape_string($userName); // Or such

"SELECT COUNT(*) FROM login WHERE userid='$userName'"

顺便说一句,IMO 最好INSERT检查插入的行数和错误代码/味精。如果那是 0 并且“...重复...”,那么您知道它正在使用中,并且可以正确处理。

于 2013-01-14T19:13:08.563 回答
0
function isUnique($userName, $link)
{
                $result = mysqli_query($link, 'SELECT `userid`
                        FROM `login`
                        WHERE `userid` = \''.$userName.'\''));
                return mysqli_num_rows($result) == 0;
}

复制自phpfreaks

于 2013-01-14T22:37:53.523 回答