1

I'm working on a social network and if a username or email is the same I don't want to enter the details into the MySQL database.

Here's the PHP I'm using:

if (isset($_POST['username']) && isset($_POST['password'])){

  $datejoined = date('m/d/Y h:i:s a', time());;
  $verified = 0;
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = $_POST['password'];

  $query = "INSERT INTO `members` (username, password, email, verified, datejoined) 
       VALUES ('$username', md5('$password'), '$email', '0', '$datejoined')";

Some help would really be appreciated!

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • You need to use `if-else` , where ever required. – Gopal Sharma Nov 08 '15 at 13:55
  • 1
    Add a unique constraint to those fields in your database? – TZHX Nov 08 '15 at 13:55
  • See http://stackoverflow.com/questions/8449540/php-detect-mysql-update-insertion-failure-due-to-violated-unique-constraint – William Nov 08 '15 at 13:55
  • first use select to see if username or email exist or not , then use if-else statement to insert into database –  Nov 08 '15 at 14:03
  • Your code is open to [SQL injection](http://www.bobby-tables.com/). Additionally MD5 is [not secure for protecting passwords](http://security.stackexchange.com/questions/19906/is-md5-considered-insecure). Switch to [password_hash](http://stackoverflow.com/questions/26536293/php-password-hash-password-verify) instead – Machavity Nov 08 '15 at 14:04
  • `md5($password)`? Really? Just left it plaintext - no difference for today. – vp_arth Nov 08 '15 at 15:09

1 Answers1

0

Create unique indexes to spot duplicates.

create unique index unq_members on members(username);
create unique index unq_members on members(email);

Then, ignore the duplicates when doing an insert:

INSERT IGNORE INTO `members`(username, password, email, verified, datejoined)
    VALUES ('$username', md5('$password'), '$email', '0', '$datejoined');

Or use:

INSERT INTO `members`(username, password, email, verified, datejoined)
    VALUES ('$username', md5('$password'), '$email', '0', '$datejoined')
    ON DUPLICATE KEY UPDATE username = username;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 1
    **Note:** the `IGNORE` part ignores more things than just the duplicate insertion. [MORE](http://stackoverflow.com/questions/548541/insert-ignore-vs-insert-on-duplicate-key-update) and [MORE](https://dev.mysql.com/doc/refman/5.6/en/insert.html) – FirstOne Nov 08 '15 at 14:15