-2

I have a problem that i can't seem to be able to solve with my register script.

Here's the script:

<?php

    //MySQLi connection

    $con = mysqli_connect("-","-","-","users");

    if (mysqli_connect_errno())

    {

    echo "MySQLi Connection was not established: " . mysqli_connect_error();

    }

    //Reading the userdata from the registerp.php page

    $usr = mysqli_real_escape_string($con,$_POST['username']);

    $email = mysqli_real_escape_string($con,$_POST['email']);

    $pass_unhashed = mysqli_real_escape_string($con,$_POST['pass']);

    $pass = password_hash($pass_unhashed, PASSWORD_DEFAULT);

    //Checking if user exists

    $check_usr = mysqli_query($con,"SELECT * FROM users WHERE user_name = '$usr'");
    if(check_usr === false)
    {
        echo(mysqli_error($con));
    }
    else
    {
        if (mysqli_num_rows($con,$check_usr)>=1)
        {
            echo "This Username already exists";
        }
        else
        {
            echo "This Username is available";
        echo "      Name:  $usr";
        }
    }
    ?>

My problem is that i can't get the verification to work (So that they can't create two accounts with the same names).

mysqli_num_rows always returns 0 ( "This Username is available" ) even though there is my test user (nevondrax) in my table

Also, it doesn't seem to give me any errors either..

What did i do wrong / What can i do to fix it?

Alok Patel
  • 7,842
  • 5
  • 31
  • 47
Nevondrax
  • 3
  • 3
  • 4
    Don't pass connection to `mysqli_num_rows` Just use it as `mysqli_num_rows($check_usr)` – Saty Jul 20 '16 at 12:40
  • 1
    Thanks a lot, i have been searching for hours and hours and couldn't find the error... Well, now it works! – Nevondrax Jul 20 '16 at 12:45
  • 1
    Well your script is open for sql injection read http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 to prevent it – Saty Jul 20 '16 at 12:47
  • Your ` if(check_usr === false)` is missing a `$` - it should be ` if($check_usr === false)` – Geoff Atkins Jul 20 '16 at 12:53
  • I'm currently reading through all that and working on getting it safe, thanks, again. @GeoffAtkins thanks for pointing that out, fixed it now. – Nevondrax Jul 20 '16 at 13:03

1 Answers1

6

mysqli_num_rows() accepts single argument of result set (mysqli_query() or mysqli_store_result() or mysqli_use_result()), So it should be,

mysqli_num_rows($check_usr);

Reference: http://php.net/manual/en/mysqli-result.num-rows.php

Alok Patel
  • 7,842
  • 5
  • 31
  • 47