drebew5059 2014-03-22 10:38
浏览 156
已采纳

检查数据库中是否已存在用户名

I'd like to make an if statement that checks if the username, already exists in the MYSQL database. I tried some different stuff, but i cant make it work. Every time I test it in my browser I get a notice

Notice: Undefined index: username in etc.

I am confused if it has anything to do with the $result variable or the $check variable or neither.

Here is the HTML form and the PHP script. https://gist.github.com/anonymous/9704354

Thank you and have a nice weekend!

  • 写回答

2条回答 默认 最新

  • douren7921 2014-03-22 10:42
    关注

    There are a few things that are wrong in your code.

    First, never place variables directly in SQL queries, thats how SQL injections happen. Start using PDO or another library for your MYSQL.

    The reason you are getting an undefined notice is because of this line.

     $result = mysql_query("SELECT * FROM users WHERE username = '$_POST[create_user]'");
    

    It should be this without fixing the huge SQL Injection flaw

     $result = mysql_query("SELECT * FROM users WHERE username = '{$_POST['create_user']}'");
    

    Also you should add a "LIMIT 1" to the end of the select query to speed things up. No need looking for more than one user.

    You can verify the user by just checking for row_count instead of checking the text values. Since MySQL is not case sensitive for some fields, username "AAAaaa" will be equal to "aaaAAA". If you check row count instead, you will be sure that no usernames are in the database of that text. Or if you want to check using PHP, make sure you pass the usernames through strtolower()

    When you start using PDO, the following example will help you.

    $dbh = new PDO() // Set the proper variables http://us2.php.net/pdo
    if(empty($_POST['create_user'])) {
       echo 'Username is Empty. Always check if POST and Get data is set';
       die();
    }
    
    $query = "SELECT * FROM `users` WHERE `username` = ? LIMIT 1;"
    $data = array($_POST['create_user']);
    $sth = $dbh->prepare($query);
    
    if(!$sth->execute($data)) {
       echo 'Handle SQL Error';
       die();
    }
    
    if($sth->rowCount() == 0) {
       echo 'Unused Username';
    }else{
       echo 'Used Username';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?