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

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 execute this script, the code in the else block is executed (even when the username inputted is one that is already present).

The table name is 'Users' and the column that I am trying to search is 'username'. The input from my form was read into $username and I verified that it was read in properly using echo. $con contains the connection to the server.

At some point I also put in echo $query (nothing was printed) and echo mysql_num_rows($query) (nothing was printed).

Here's the relevant segment of the code. Would really appreciate some tips.

$query = mysql_query("SELECT username FROM Users WHERE username=$username", $con);

  if (mysql_num_rows($query) != 0)
  {
      echo "Username already exists";
  }

  else
  {
    ...
  }

EDIT: Apparently I was supposed to be using mysqli for my server and the way I checked the num_rows for that was by doing $query->num_rows since it was a property of the object. Thanks for all the help!

This question is related to php mysql sql

The answer is


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

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


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


$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$pass = $_POST["password"];

$check_email = mysqli_query($conn, "SELECT Email FROM crud where Email = '$email' ");
if(mysqli_num_rows($check_email) > 0){
    echo('Email Already exists');
}
else{
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $result = mysqli_query($conn, "INSERT INTO crud (Firstname, Lastname, Email, Password) VALUES ('$firstname', '$lastname', '$email', '$pass')");
}
    echo('Record Entered Successfully');
}

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

Use prepared statements, do not use mysql as it is deprecated.

// check if name is taken already
$stmt = $link->prepare("SELECT username FROM users WHERE username = :username");
$stmt->execute([
    'username' => $username
]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (isset($user) && !empty($user)){
    // Username already taken
}

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(*).


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!


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.


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
   {
     ...
    }

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database