user3733831
user3733831

Reputation: 2926

Insert multiple rows in mysqli prepared statement

I do have 3 mysql tables "users", "banks", and "user_bank". Every users must have at least one bank and maximum is two.

When users signup to system I need to insert bank details to user_bank table also.

This is how I tried it:

$success=FALSE; 

if($success == FALSE) {
    $query = "INSERT INTO user_bank ( 
                                  beneficiary_id
                                , beneficiary_bank_id
                                , branch_id
                                ) VALUES (?, ?, ?)";
    $stmt = $mysqli->prepare($query);           
    $stmt->bind_param('iii', $lastInsertId
                           , $bank_one
                           , $branchId_one
                     ); 
    $stmt->execute();

    if ($stmt->affected_rows == 1) {                        
        $success=TRUE; 

        if(!empty($bank_two) && !empty($branchId_two)) {

            $query = "INSERT INTO user_bank ( 
                                            id
                                            , bank_id
                                            , branch_id
                                            ) VALUES (?, ?, ?)";
            $stmt = $mysqli->prepare($query);           
            $stmt->bind_param('iii', $lastInsertId
                                   , $bank_two
                                   , $branchId_two
                             ); 
            $stmt->execute();   
            $success=TRUE; 
        }
    }
}

if ($success == TRUE) {
    $messages = array('success'=>true, 'message'=>'You successfully registered.');
}  

My question is, can anybody tell me I there a way to use a single query for this? If so how its doing?

Hope somebody may help me out. Thank you.

Upvotes: 1

Views: 1077

Answers (1)

Vlatko Šurlan
Vlatko Šurlan

Reputation: 444

You need to learn to read the MySQL manual. If you check out the INSERT definition you find this for the VALUES specification:

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. Example:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

Upvotes: 1

Related Questions