1

I have a registration form and after pressing the 'register' button, I'd like to check the database and see if that user already exists and if so return an error message "name already exists" and if it does not, of course, I'd like it to register the user. I found multiple other solutions that were asked before but nothing really worked. After many modifications the current code is this:

?php 

if(isset($_POST['register'])) {

    session_start();
    $FName = $_POST['firstname'];
    $LName = $_POST['lastname'];
    $Email = $_POST['email'];
    $PW = $_POST['password'];
    $servername = "localhost";
    $username = "root";
    $password = "root";
    $dbname = "users_db_physicians";
    $conn = new mysqli($servername, $username, $password, $dbname);
    $result_x = $conn->query("SELECT FROM users_database (username) WHERE username = '$Email'");
    if (mysqli_num_rows($result_x)>=1) {
    echo "name already exists";
    }
    else
    {
    $conn->query("INSERT INTO users_database (first_name, last_name, username, password)Values('{$FName}', '{$LName}', '{$Email}', '{$PW}')");
    header('Location: login.php');
    echo "it works";
    }


    }
?> 

Now so far, with the above code, the only thing that happens is that the user gets registered (I checked the table and its updated) and the page moves to login.php so I am guessing the ELSE is working only and no row is generated or the if statement is buggy.

Please help.

appreciate your time, oliver_foxx

oliverfoxx
  • 105
  • 8
  • 1
    you aren't selecting any columns so i would guess your query fails. `SELECT FROM` – bassxzero Apr 13 '16 at 22:38
  • 1
    To the top of your script, add `error_reporting(E_ALL); ini_set('display_errors', 1);` A SQL syntax problem with your `SELECT` statement is causing `$result_x` not to be a result resource, and the else case is executing, but you are not seeing the error. – Michael Berkowski Apr 13 '16 at 22:40
  • 2
    The select should take the form of `SELECT username FROM users WHERE username = 'the name'` but instead of calling `query()`, it is important to use `prepare()/bind_param()/execute()` with a `?` placeholder for the username in MySQLi to ensure safety against SQL injection (there are other ways, but this is preferred) See [How can I prevent SQL injection in PHP](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) for MySQLi examples – Michael Berkowski Apr 13 '16 at 22:42
  • Thank folks, @MichaelBerkowski the SELECT structure was faulty, I copied it from another post and I failed miserably to notice it. I will work on the SQL injection prevention. thankz alot! – oliverfoxx Apr 13 '16 at 22:53

0 Answers0