문제

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

}

도움이 되었습니까?

해결책

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'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top