麻烦PHP,PDO和MySQL

时间:2015-07-14 00:09:15

标签: php mysql pdo

我正在建立一个脚本来将商品添加到购物车..

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

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

在下面的代码中,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();

        }

    }   

}

2 个答案:

答案 0 :(得分:1)

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

我相信如果没有更新行,那么它会返回0以查看受影响的行的数量,而不是例外。

答案 1 :(得分:0)

您必须更改语句的顺序: 只需将INSERT放在UPDATE之前,因为如果记录已经存在,INSERT将捕获异常。 UPDATE不会。