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