Jump to content
Tom18

Check if username already exists

Recommended Posts

Hello i am trying to create a prepared statement with mysqli and php to see if the username entered in the HTML form already exists the in table.

I am getting this error 

Fatal error: Uncaught Error: Call to a member function bind_param() on string

My code:

    $sql_u = "SELECT user FROM users WHERE user=?";
    $sql_u->bind_param('s', $user);
    $sql_u->execute();

    if($result = $sql_u->fetch_array()) {
	if($result >= 1) {
	    print "That username is taken!\n";
	} else {
	    //Do nothing
	}

    }

The variable $user is equal to $_POST['user'];

The code below is working it inserts records into the table with no problems but i would just like to check if the user is already existing.

    $stmt = $conn->prepare("INSERT INTO users (user, password, email) VALUES (?, ?, ?)");
    $stmt->bind_param('sss', $user, $pass, $email);
    $stmt->execute();

    if(!$stmt) {
	die("Something went wrong.");
    }

 

Share this post


Link to post
Share on other sites

If you look at your second block of code you will see you are using prepare() method.

That bit is missing from the first block - you are defining a string instead of a prepared statement. bind_param() needs a statement object.

 

EDIT: BTW fetch_assoc() returns an array, not a numeric value.

Edited by Barand

Share this post


Link to post
Share on other sites

 Your your logic is incorrect. You do not check to see if the user already exists. You set a unique constraint on the username column and then attempt the insert capturing the duplicate error if any. Your method will create a race condition.

Share this post


Link to post
Share on other sites

For starters, a string is not an object

    $sql_u = "SELECT user FROM users WHERE user=?";
    $sql_u->bind_param('s', $user);
    $sql_u->execute()

Therefore, the bind_param function does not exist; and nor does execute

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.