Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

php

mysql

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!

like image 923
covfefe Avatar asked Nov 30 '13 05:11

covfefe


People also ask

How do you check if username already exists in php MySQL?

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

How do you check if value already exists in MySQL database in php?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do you check if data already exists in SQL database?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How can we avoid duplicate username and email in your database using php and MySQLi?

-- Make it unique ALTER TABLE users ADD UNIQUE (username); This will prevent duplicate records in the table with the same username. When you try to insert the same one then an error will be generated. You can then catch the exception in PHP and check the reason.


1 Answers

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

like image 85
Renish Khunt Avatar answered Sep 22 '22 23:09

Renish Khunt