PHP PDO SQLite. Transaction and updating problems -
i have problem transaction in php-pdo-sqlite , updating.
$db = new pdo('sqlite:database1.sqlite'); /* $rowsnumber1 = $db->exec("create table if not exists questions( id integer primary key autoincrement, question text not null, answers integer not null )"); print('$rowsnumber1: '.$rowsnumber1.'<br />'); $rowsnumber2 = $db->exec("create table if not exists answers( id integer primary key autoincrement, qid integer not null, answer text not null )"); print('$rowsnumber2: '.$rowsnumber2.'<br />'); */ //print('inserting: '); $res = $db->exec("insert questions (question,answers) values ('question',0)"); var_dump($res); print('<br />'); $qid = 1; try { $db->setattribute(pdo::attr_errmode, pdo::errmode_exception); $db->begintransaction(); // variant 1 //print('executing 1: '); $res1 = $db->exec("insert answers (qid,answer) values ($qid,'answer')"); var_dump($res1); print('<br />'); //print('executing 2: '); $res2 = $db->exec("update questions set answers = answers+1 id = '".$qid."'"); var_dump($res2); print('<br />'); // variant 2 print('preparing 1: '); $statement1 = $db->prepare("insert answers (qid,answer) values (:qid,:answer)"); var_dump($statement1); print('<br />'); print('preparing 2: '); $statement2 = $db->prepare("update questions set answers = answers+1 id='".$qid."'"); var_dump($statement2); print('<br />'); print('executing 1: '); $res1 = $statement1->execute(array('qid'=>$qid,'answer'=>'answer')); var_dump($res1); print('<br />'); print('executing 2: '); $res2 = $statement2->execute(); var_dump($res2); print('<br />'); $db->commit(); } catch(exception $e) { $db->rollback(); print("transaction failed: " .$e->getmessage()); }
there no problem when "id" of question , "qid" of answer same ($qid). problem begins when try insert answer "id" of question, doesn't exist in table "questions". example, in table "questions" there 1 question ("id" "1") , try insert answer question "id" = "5". answer inserted, question not updated (the cell "answers" not incremented) because there no question such "id" = "5". matter transaction doesn't make rollback , updating executed result "true", though there no updating. wrong transaction , why updating returns "true" when use statement ?
i have understood did wrong. matter there no logic in 'try' section. before $db->commit(); should have written next 2 lines:
if($res1 != 1) throw new exception("inserting answer failed"); if($res2 != 1) throw new exception("updating question failed");
about prepare(); , execute(); - have read inattentively manual of pdo here http://www.php.net/manual/en/pdostatement.execute.php matter execute(); returns 'true' in case statement executed, doesn't check whether or not affected row. , method exec(); checks if row affected. i.e. methods prepare(); , execute(); not suitable in situation. should have used 'variant 1', commented.
Comments
Post a Comment