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

Asked

Viewed 113 times

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 facilitate but I have never seen a registration page that worked that way.

Additional details:

  • I’m using the codes correctly, for each of the else has a if in the code.
  • In the database there is a table users and within the table has username and email
  • The 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';
        }
    }
    
  • pq the two queries, one with only one or would not solve?

  • as a matter of convenience for the user to know if the email or username are already in use or both(which in the case of bind_param of Fatal error). No mysqli -> query this could be done easily. If it is not possible I will have to use mysqli -> query again to check and bind_param to enter the data in the database.

1 answer

3

The PHP error message fools a little. You need to "close" the first statement by calling the method close after fetch. In this 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 the fetch did not consume all the "buffer" of the query - that is, your first Prepared statement is still allocated and consuming resources (you can only have one "open" query per connection at a time). The close releases these features and ensures that you can perform another query in that connection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.