Using two statment at the same time without giving "Fatal error: bind_param"

1

On my records page, I want to check the names of users and emails separately but at the same time.

I could leave the message like this: Username or email already exists to make it easier but I've never seen a registration page that works that way.

Additional details:

  • I am using the codes correctly, for each of the else has a if in the code.
  • In the database there is the users table and inside the table has username and email
  • stmt are working separately.

    $username = $_POST['username'];
    $email = $_POST['email'];
    $id = '';
    
    else{
    
    $stmt = $mysqli -> prepare('SELECT id FROM users WHERE username = ?');
    $stmt -> bind_param("s", $username);
    $stmt -> execute();
    $stmt -> bind_result($id);
    $stmt -> fetch();
    
        if($id > 0){
            $user_error = 'Username already exists';
        }
    
    }
    
    else{
    
    $stmt = $mysqli -> prepare('SELECT id FROM users WHERE email = ?');
    $stmt -> bind_param("s", $email);
    $stmt -> execute();
    $stmt -> bind_result($id);
    $stmt -> fetch();
    
        if($id > 0){
            $email_error = 'Email already exists';
        }
    }
    
asked by anonymous 07.06.2014 / 04:06

1 answer

3

The PHP error message fools a bit. You need to "close" the first statement, calling the method close after fetch. In case, your code would look something like this:

$stmt = $mysqli -> prepare('SELECT id FROM users WHERE username = ?');
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();
$stmt->close(); // Liberando recursos
if ($id > 0) {
    $user_error = 'Username already exists';
}

This happens because fetch did not consume the entire query buffer - that is, your first prepared statement is still allocated and consuming resources (you can only have one query "open" per connection at a time). close frees these features and ensures that you can execute another query on that connection.

    
04.08.2014 / 02:30