mysql - SQL IF EXIST UPDATE ELSE INSERT prepared statement -


i'm breaking brains on this, realy appriciate help!

this code have far..

$conn = db_connect();                        $sql = "insert measurements (`date`, `weight`, `waist`, `id`) values (?,?,?,?)"; $stmt = $conn-> prepare($sql);  $stmt ->bind_param("sddi", $date, $_post['weight'], $_post['waist'], $user_id); $stmt->execute(); $stmt->close(); $conn->close(); 

its prepared statement sql insert. want change if exist update else insert way doing right now. prepared statement:

if exists  (select * measurements user_id=’4’) update measurements set (`weight`=40, `waist`=45) user_id=’4’ else insert measurements  values (`date`='week 1', `weight`= 40, `waist`=45, `id`=4) 

i found articles on stackoverflow if exist update else insert did not find prepared statement in worked me.

thanks thousand!

update:

i've changed dublicate key style.

$sql = " insert measurements (uniqueid, date, weight, waist)  values ('$uniqueid', '$date', '$weight',  '$waist')  on duplicate key update weight= '$weight', waist= '$waist'";  $conn->query($sql); 

now second part of question, how make prepared statement?

to implement mr. jones' solution mysqli prepared statement, code thus:

$sql = "insert measurements             (`uniqueid`, `date`, weight, waist)            values             (?, ?, ?, ?)            on duplicate key             update weight = ?, waist = ?"; $stmt = $conn->prepare($sql);  $stmt ->bind_param("isdddd", $user_id, $date, $_post['weight'], $_post['waist'], $_post['weight'], $_post['waist']); $stmt->execute(); 

a cleaner implementation use pdo:

$sql = "insert measurements             (`uniqueid`, `date`, weight, waist)            values             (:uniqueid, :date, :weight, :waist)            on duplicate key             update weight = :weight, waist = :waist"; /* $conn pdo object */ $stmt = $conn->prepare($sql); $stmt->execute(array(':uniqueid' => $user_id, ':date' => $date, ':weight' => $_post['weight'], ':waist' => $_post['waist'])); 

note named placeholders, can use same name in more 1 place , need assign value once.