ON DUPLICATE KEY插入新记录而不是使用Unique键进行更新

时间:2016-04-06 20:18:50

标签: php mysql

我有一个问题,我的INSERT ... ON DUPLICATE KEY UPDATE正在插入新记录而不是更新行,我正在使用的表同时具有主键和唯一键。所以我很困惑为什么会这样。

CREATE TABLE `Product` (
`Product_Id` bigint(255) NOT NULL AUTO_INCREMENT,
`Resturant_ID` bigint(255) NOT NULL,
`Product_Desc` text NOT NULL,
`Product_Name` varchar(100) NOT NULL,
`Product_Price` decimal(8,0) NOT NULL,
`Add_On_ID` int(11) NOT NULL,
 PRIMARY KEY (`Product_Id`),
 UNIQUE KEY `Product_Name` (`Product_Name`)
 ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8

QUERY

   $add_product_errors = array();
    if (isset($_POST['add'])) {
        $item_name = $_POST['item_name'];
        $desc = $_POST['desc'];
        $price = $_POST['price'];
        $rest_id = mysqli_real_escape_string($dbc, $_SESSION['Resturant_ID']);
        if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) {
            $add_product_errors['price'] = "Please enter a product price";
        }
        if (empty($_POST['item_name'])) {
            $add_product_errors['item_name'] = "Please enter a name";
        }
        if (empty($_POST['desc'])) {
            $add_product_errors['desc'] = "Please enter a product description";
        }
        $query = "INSERT INTO Product(Resturant_ID,Product_Name,Product_Desc,Product_Price) VALUES (?,?,?,?) 
            ON DUPLICATE KEY 
              UPDATE
              Resturant_ID = VALUES(Resturant_ID)
             ,Product_Name = VALUES(Product_Name)
             ,Product_Desc = VALUES(Product_Desc)
             ,Product_Price = VALUES(Product_Price)";
        $run_query = mysqli_prepare($dbc, $query);
        if (!$run_query) {
            die(mysqli_error($dbc));
        }
        mysqli_stmt_bind_param($run_query, 'sssd', $rest_id, $item_name, $desc, $price);
        $execute = mysqli_stmt_execute($run_query);
        $item_name = strip_tags($_POST['item_name']);
        $desc = strip_tags($_POST['desc']);
        //100 - changes the way the decimal displays in database
        $price = strip_tags($_POST['price'] * 100);
        if ($execute) {
            echo "<script> alert('Addrrss Saved')</script>";
        } else {
            echo "<b>Oops! we have an issue </b>";
            mysqli_stmt_close($run_query);
        }
    }
    ?>

1 个答案:

答案 0 :(得分:2)

语法只是向我看。也许尝试编写SQL并首先在控制台或MySQL工作台中进行测试或先测试?试试这个:

$query = "INSERT INTO Product(Resturant_ID,Product_Name,Product_Desc,Product_Price) VALUES (?,?,?,?) 
    ON DUPLICATE KEY UPDATE
        Resturant_ID = ?
        ,Product_Name = ?
        ,Product_Desc = ?
        ,Product_Price = ?";

    $run_query = mysqli_prepare($dbc, $query);
    if (!$run_query) {
        die(mysqli_error($dbc));
    }
    mysqli_stmt_bind_param($run_query, 'issdissd', $rest_id, $item_name, $desc, $price, $rest_id, $item_name, $desc, $price);

或者可能是?八次并且两次绑定事物......如果mysqli支持命名参数,则不能确定...

根据Martin的反馈更新[再次]。