0

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

}

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
meztli
  • 449
  • 2
  • 9
  • 20

1 Answers1

1

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'
worenga
  • 5,776
  • 2
  • 28
  • 50
  • the function now looks like this: 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 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'); } } But only the Insert portion of it is working :S – meztli Dec 09 '13 at 16:39