Prepared Statement with ON DUPLICATE KEY

前端 未结 2 1557
执念已碎
执念已碎 2020-12-17 15:58

I think this one should be pretty easy but I am having trouble getting it right. I have searched a bit but being new to prepared statements I can\'t quite figure out the sy

相关标签:
2条回答
  • 2020-12-17 16:22

    I'd strongly suggest having a look at something like Doctrine DBAL (not ORM) - it allows you to heave key => value pairs and makes these types of operations easier to wield when there's so many values.

    You can then do something like:

    try {
        $conn->insert(
        'db.`table`',
         [
           'city' => $city,
           'state' => $state
         ]);
    } catch (Exception $e) {
    
        if( $e->getCode() !== '23000' ) {
            throw $e;
        }
    
        $conn->update(
        'db.`table`',
         [
           'city' => $city,
           'state' => $state
         ],
         [
           'user' => $user
         ]);
    }
    
    0 讨论(0)
  • 2020-12-17 16:24

    The easiest way to use INSERT...ON DUPLICATE KEY UPDATE is to use the VALUES clause in the following way, so you don't need to repeat the parameters in the UPDATE clause. They just use the same values for each column that you passed in the VALUES clause:

    if($stmt = $mysqli -> prepare("
        INSERT INTO user_info (city, state, website, public_contact, 
            user, zipcode, pic, emailme)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?) 
        ON DUPLICATE KEY UPDATE
            city = VALUES(city),
            state = VALUES(state),
            website = VALUES(website),
            public_contact = VALUES(public_contact),
            user = VALUES(user),
            zipcode = VALUES(zipcode),
            pic = VALUES(pic),
            emailme = VALUES(emailme)") {
        $stmt -> bind_param("sssssssi",$city, $state, $website, $public_contact, 
            $user, $zipcode, $pic, $emailme);
        $stmt -> execute();
        $stmt -> close();
    }
    

    The IODKU syntax requires that you set each column individually. You can't list them all in one clause like you were trying to do.

    You should always report any errors from any call to prepare() or execute(). Or you can make mysqli throw exceptions:

    $mysqli -> report_mode = MYSQLI_REPORT_STRICT;
    

    Also, you don't need to bind_result(), since there is no result set from INSERT:

    // NO: $stmt -> bind_result($result);
    
    0 讨论(0)
提交回复
热议问题