Trying to check if username already exists in MySQL database using PHP

后端 未结 8 1842
无人共我
无人共我 2020-12-28 10:12

I\'ve looked at the many other posts that were similar to my issue and implemented their solutions (as far as I can tell) as exactly as I could. However, every time I execut

相关标签:
8条回答
  • 2020-12-28 10:41

    Here's one that i wrote:

    $error = false;
    $sql= "SELECT username FROM users WHERE username = '$username'";
    $checkSQL = mysqli_query($db, $checkSQL);
    
    if(mysqli_num_rows($checkSQL) != 0) {
       $error = true;
       echo '<span class="error">Username taken.</span>';
    }
    

    Works like a charm!

    0 讨论(0)
  • 2020-12-28 10:45

    change your query to like.

    $username = mysql_real_escape_string($username); // escape string before passing it to query.
    $query = mysql_query("SELECT username FROM Users WHERE username='".$username."'");
    

    However, MySQL is deprecated. You should instead use MySQLi or PDO

    0 讨论(0)
  • 2020-12-28 10:46

    TRY THIS ONE

     mysql_connect('localhost','dbuser','dbpass');
    
    $query = "SELECT username FROM Users WHERE username='".$username."'";
    mysql_select_db('dbname');
    
        $result=mysql_query($query);
    
       if (mysql_num_rows($query) != 0)
       {
         echo "Username already exists";
        }
    
        else
       {
         ...
        }
    
    0 讨论(0)
  • 2020-12-28 10:47

    Try this:

    $query = mysql_query("SELECT username FROM Users WHERE username='$username' ")
    

    Don't add $con to mysql_query() function.

    Disclaimer: using the username variable in the string passed to mysql_query, as shown above, is a trivial SQL injection attack vector in so far the username depends on parameters of the Web request (query string, headers, request body, etc), or otherwise parameters a malicious entity may control.

    0 讨论(0)
  • 2020-12-28 10:47

    PHP 7 improved query.........

    $sql = mysqli_query($conn, "SELECT * from users WHERE user_uid = '$uid'"); if (mysqli_num_rows($sql) > 0) { echo 'Username taken.'; }

    0 讨论(0)
  • 2020-12-28 10:52

    Everything is fine, just one mistake is there. Change this:

    $query = mysql_query("SELECT username FROM Users WHERE username=$username", $con);
    $query = mysql_query("SELECT Count(*) FROM Users WHERE username=$username, $con");
    
    if (mysql_num_rows($query) != 0)
    {
        echo "Username already exists";
    }
    else
    {
      ...
    }
    

    SELECT * will not work, use with SELECT COUNT(*).

    0 讨论(0)
提交回复
热议问题