简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM