检查数据库中的用户名,避免重复

时间:2012-06-11 05:20:27

标签: php mysql database phpmyadmin

如果存在同名的现有用户,我想对我的数据库进行查询。然后我想发送一个“返回假”。但我现在只得到一个felmeddalnde。

  

警告:mysql_num_rows()将参数1视为资源,布尔值

function DoInsertNewUser($name, $password) {
    var_dump($name);
    var_dump("inne i databasen");
    //tar kontakt med databasen
    $DBConnection = new DBConnection();
    $DBConnection -> Connect();

    $result = mysql_query("SELECT m_username FROM user WHERE m_username ='$name'");
    $number_of_rows = mysql_num_rows($result);

    var_dump($number_of_rows);

    if ($number_of_rows  > 1) {
        var_dump('Användarnamnet finns redan');
    }
    else 
    {
        //ställer en sql-fråga.
        $sql = "INSERT INTO `user`(`m_username`,`m_password`) VALUES (?,?)";

        $stmt = $DBConnection -> prepare($sql);
        $stmt -> bind_param("ss", $name, $password);
        if ($stmt === FALSE) {

            return false;
        }

        $stmt -> execute();
        // ger resultet.
        while ($stmt -> fetch()) {
            $stmt -> close();
            return true;
        }
        $stmt -> close();
        return false;
    }
}

2 个答案:

答案 0 :(得分:2)

您只需计算拥有该用户名的用户数。

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Not connected : ' . mysql_error());
 }

$db_selected = mysql_select_db('db_name', $link);
if (!$db_selected) {
   die ('Can\'t use db_name : ' . mysql_error());
}
$result = mysql_query("SELECT COUNT(*) AS count FROM user WHERE m_username ='".$name."'", $link) or die(mysql_error());

$count = mysql_fetch_assoc($result)['count'];

根据需要更新localhost,mysql_user,mysql_password和db_name。

答案 1 :(得分:1)

替换

$result = mysql_query("SELECT m_username FROM user WHERE m_username ='$name'");

$result = mysql_query("SELECT m_username FROM user WHERE m_username ='$name'") or die(mysql_error());