-1
<?php
   include("config.php"); // Just connects the database as $db
   session_start();

   if($_SERVER["REQUEST_METHOD"] == "POST") {
      // username and password sent from form 

      $myusername = 'a';
      $mypassword = 'a';



      $sql = "SELECT id FROM users WHERE username = '$myusername'";
      $result = mysqli_query($db,$sql);
      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
      $active = $row['active'];
      $count = mysqli_num_rows($result);
      if(count == 0) {
          $sql = "insert into users values (NULL, '$myusername', '$mypassword');";
          $result = mysqli_query($db,$sql);


          echo "succesful";
          exit();
      }

      echo "Username already taken";
      exit();



   }
?>

Basically. I want it to NOT create another row if username is already found. The table is

id   username   password
1      a           b
2      s           a

The username is unique and the id autoincrements.

The problem with above code is that it always creates a row even if username is taken. For some reason $count = mysqli_num_rows($result); doesn't output anything but 0, why?

Consider the table I gave and run that code again. It should output "Username is already taken" instead it creates another row such that

id   username   password
1      a           b
2      s           a
3      a           a
e t
  • 243
  • 2
  • 11
  • 2
    Don't rely on code for this, set username to a unique index in the DB, and then catch for the duplicate key error. This insures that is 100% impossible to add 2 users with the same name, which for me is a security concern and must be build in a way that will never break. – ArtisticPhoenix Mar 28 '18 at 00:54
  • 2
    Your if statement has a syntax error... you're referencing a constant and not the $count var... is that just a transpose error? – John Mar 28 '18 at 00:54
  • ohhhhhhhhhhhh sorry new to php. Works now by the way. – e t Mar 28 '18 at 00:56
  • This is also a bad idea `"SELECT id FROM users WHERE username = '$myusername'"` as you probably intend to fill that in with end user data which means you will have SQLInjection vulnerabilities. – ArtisticPhoenix Mar 28 '18 at 00:57
  • Okay that makes sense I'll be sure to use that – e t Mar 28 '18 at 00:58
  • 1
    @e-t everybody wrestles with syntax errors right underneath our noses... welcome to programming... won't be the last time that happens :-) – John Mar 28 '18 at 00:59
  • 2
    Exactly my point, syntax errors should not create security issues of the level of giving someone access to another persons account. You have to know without a doubt that the Username will not be duplicated no matter what, just saying. – ArtisticPhoenix Mar 28 '18 at 01:00

1 Answers1

-1

You issue is this

  if(count == 0)

Change it to

  if($count == 0)

and all will be fine

Forbs
  • 1,256
  • 1
  • 7
  • 9