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条)

报告相同问题?

悬赏问题

  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)