Jump to content

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.");
    }

 

Link to comment
https://forums.phpfreaks.com/topic/307683-check-if-username-already-exists/
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

 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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.