Trouble with PHP, PDO, and MySQL -
i'm building script add item shopping cart..
i want first check see if there's existing cart table user. if not, want create new table shopping cart.
if there table, want see if current item in it. if is, want update quantity. if it's not in table, want add new row.
in code below, update statement firing whether there itemnumber
match or not. means there's no exception, , new row not being inserted new new itemnumber
. else working expected.
try { // create shopping cart. if exists, throw 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 far cart has been newly created. insert item information cart $cartdb->setattribute( pdo::attr_errmode, pdo::errmode_exception ); $sql = 'insert `' . $table . '` (`itemnumber`, `title`, `price`, `color`, `size`, `quantity`, `category`, `photo`) values ("' . $itemnumber . '", "' . $title . '", "' . $price . '", "' . $color . '", "' . $size . '", "' . $quantity . '", "' . $category . '", "' . $photo . '");'; $cartdb->exec($sql); } catch(pdoexception $e) { // got exception == not insert data table echo $e->getmessage(); } } catch(pdoexception $e) { // got exception == table exists echo $e->getmessage(); try { // first see if item number in table $cartdb->setattribute( pdo::attr_errmode, pdo::errmode_exception ); $sql = "update `" . $table . "` set `quantity` = `quantity` + " . $quantity . " `itemnumber` = '" . $itemnumber . "'"; $cartdb->exec($sql); } catch(pdoexception $e) { // exception thrown == item number not yet in table echo $e->getmessage(); try { $cartdb->setattribute( pdo::attr_errmode, pdo::errmode_exception ); $sql = 'insert `' . $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(); } } }
i assign value of exec()
statement variable like: $return = $cartdb->exec($sql);
echo variable.
i believe if no rows updated returns 0
count of affected rows , not exception.
Comments
Post a Comment