ON DUPLICATE KEY UPDATE in public function php not working

342 views Asked by At

I am new to php and working on a pdo crud class. My insert function by itself works, but I am trying to have one function for both insert and update. I researched and saw that you can use ON DUPLICATE KEY UPDATE to do this, but when I add it to my function it does not work.

Here is my original INSERT that works;

//INSERT
public function insert($product_name,$color,$description,$used_for){
    $query="INSERT INTO makeup SET product_name='$product_name', color='$color', description='$description', used_for='$used_for'";
    $result= $this->mysqli->query($query) or die(mysqli_connect_errno()."product cannot inserted");

    if($result){
        header('location:read.php');    
    }
}

and here is the one with the added ON DUPLICATE KEY UPDATE (not working) no error messages, items simply do not update or insert

//INSERT and UPDATE
public function insert($product_name,$color,$description,$used_for){
    $query="INSERT INTO makeup SET product_name='$product_name', color='$color', description='$description', used_for='$used_for'
    ON DUPLICATE KEY UPDATE makeup SET product_name='$product_name', color='$color', description='$description', used_for='$used_for'";
    $result= $this->mysqli->query($query) or die(mysqli_connect_errno()."product cannot inserted");

    if($result){
        header('location:read.php');    
    }
}

and called by using:

include('Crud_class.php');
if(isset($_REQUEST['submit'])){
    $obj=new Crud("localhost","root","password","dbname");
extract($_REQUEST);
$obj->insert($product_name,$color,$description,$used_for);

}

1

There are 1 answers

1
worenga On BEST ANSWER

There is a syntax error. There is no ON DUPLICATE KEY UPDATE tablename SET instead use

INSERT INTO makeup SET product_name='$product_name', color='$color', description='$description', used_for='$used_for'
    ON DUPLICATE KEY UPDATE product_name='$product_name', color='$color', description='$description', used_for='$used_for'