我正在构建将商品添加到购物车的脚本。

我想先检查一下是否存在该用户的购物车表。如果没有,我想为购物车创建一个新表。

如果已经有一个表,我想看看当前项是否已经在其中。如果是,那么我只想更新数量。如果表中还没有它,那么我想添加一个新行。

在下面的代码中,UPDATE语句将触发是否存在itemNumber匹配项。这意味着没有例外,并且不会为新的itemNumber插入新行。其他一切都按预期工作。

try {

    // create the shopping cart. If it already exists, throw an exception

    $cartDb->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); //Error Handling
    $sql = 'CREATE TABLE `' . $table . '` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `itemNumber` VARCHAR(100) NOT NULL, `title` TEXT NOT NULL, `price` VARCHAR(20) NOT NULL, `color` VARCHAR(100) NOT NULL, `size` CHAR(20), `quantity` INT(5) NOT NULL, `category` TEXT NOT NULL, `photo` TEXT NOT NULL);';
    $cartDb->exec($sql);

    try {

        // if you get this far then the cart has been newly created. Insert the item information into the cart

        $cartDb->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sql = 'INSERT INTO `' . $table . '` (`itemNumber`, `title`, `price`, `color`, `size`, `quantity`, `category`, `photo`) VALUES ("' . $itemNumber . '", "' . $title . '", "' . $price . '", "' . $color . '", "' . $size . '", "' . $quantity . '", "' . $category . '", "' . $photo . '");';
        $cartDb->exec($sql);

    } catch(PDOException $e) {

        // we got an exception == could not insert the data into the table

        echo $e->getMessage();

    }

} catch(PDOException $e) {

    // we got an exception == table already exists

    echo $e->getMessage();

    try {

        // first see if the item number is already in the table

        $cartDb->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sql = "UPDATE `" . $table . "` SET `quantity` = `quantity` + " . $quantity . " WHERE `itemNumber` = '" . $itemNumber . "'";
        $cartDb->exec($sql);

    } catch(PDOException $e) {

        // exception thrown == item number is not yet in the table

        echo $e->getMessage();

        try {

            $cartDb->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $sql = 'INSERT INTO `' . $table . '` (`itemNumber`, `title`, `price`, `color`, `size`, `quantity`, `category`, `photo`) VALUES ("' . $itemNumber . '", "' . $title . '", "' . $price . '", "' . $color . '", "' . $size . '", "' . $quantity . '", "' . $category . '", "' . $photo . '");';
            $cartDb->exec($sql);

        } catch(PDOException $e) {

            echo $e->getMessage();

        }

    }

}

最佳答案

我会将您的exec()语句的值分配给一个变量,例如:$return = $cartDb->exec($sql);然后回显该变量。

我相信,如果没有行被更新,那么它将为受影响的行的计数返回0,而不是异常。

10-04 11:16
查看更多